0

My program for initials.c found in pset 2 keeps crashing. I am new to programming so any help for the reason behind this would be great.

The pset gives these instructions:

Write a program that prompts a user for their name (using GetString to obtain their name as a string ) and then outputs their initials in uppercase with no spaces or periods, followed by a newline ( \n ) and nothing more. You may assume that the user’s input will contain only letters (uppercase and/or lowercase) plus single spaces between words. Edit: A name with multiple words (ex: John Jacob Jingleheimer Smith) can be assumed.

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main (void)
{
    char* s[] = {GetString()};
    int n = strlen(*s);

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < 1; j++)
        {
            printf("%c", toupper(s[i][j]));
        }
    }
    printf("\n");
}
2
char* s[] = {GetString()};

That declares an array of strings, not one string. So when GetString() returns, it puts the string into s[0]. As there is only one entry in the array, that is all that s holds.

In your loop, therefore, toupper(s[0][0]) will work fine, because s[0] exists. But next time through s[1] will cause a segfault, because it doesn't exist.

If you only want one string, you should declare it as char* s = GetString(); without the square brackets. Then, the call to strlen should only be strlen(s).

That will get you past the segfault, but you'll find your code then simply capitalizes each letter in the word. You'll need to rethink how you determine which character in the string (the character array) needs to be printed.

edit to add A string can contain spaces, so "Robert Louis Stevenson" is one string, and the initials exercise is asking you to take that string and print out the first character 'R' and any subsequent character that has followed a space: 'L' and 'S'.

3
  • Could you look at it again with the idea that the name will be multiple? I am trying to print the first char of each string in an array. – Joan_Dewey Jul 21 '15 at 0:52
  • No, you are trying to print each character that was preceded by a space in one string. Please see my edit to my answer. – curiouskiwi Jul 21 '15 at 0:56
  • Upvoted! :) Good job kiwi! – i_am_david Jul 21 '15 at 2:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .