0

I have one problem with this code please help me!

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


    int main(void)
    {
        printf("Please, type your name: ");
        string s=get_string();
        int i=0;
        if (s!=NULL)
        {
            printf("%c",toupper(s[0]));
            while (s!=NULL)   
            {   
                if (s[i]==' ')
                {
                        printf("%c",toupper(s[i+1]));
                }

                i++;
            }
        }
        printf("\n");

    }

I put as input: juan pablo and I get the following

~/workspace/pset2/ $ ./initials
Please, type your name: juan pablo
JPSegmentation fault
~/workspace/pset2/ $

----THEN I TRY USING THE CHECK50 AND I HAVE THE FOLLOWING ANSWER-> ~/workspace/pset2/ $ check50 ~/workspace/pset2/initials initials.c

Checking. invalid ID
~/workspace/pset2/ $
1

While working with your code, I seemed to notice that i++ would keep going on forever as long as the string was not invalid. This would mean that as it keeps looping and looping, eventually you would try to print values of the array that are invalid, thus leading to your segmentation error.

while (s!=NULL)
{
if (s[i]==' ') { printf("%c",toupper(s[i+1])); } i++ }

As you can see, if the string is not null, (which you already checked for prior) it will continue to loop as your condition will always be true while always making i bigger.

3
  • Thank you Davis, but, how am I supposed to to go on until the user stops typing in a name? I mean, what kind of loop or condition should i instead put? since I use while (s!=NULL), i also used while (s!='\0'). So how is the compiler supposed to understand and recognize the end of the string?? Jun 2 '17 at 9:07
  • Perhaps use the strlen() function. This will get the length of the string, and can use that to make a loop run only until the end of the string. Maybe try using for loops as you can have your loop run until i < strlen(string)
    – Davis
    Jun 2 '17 at 15:02
  • codehellocode
    – SarPach
    Aug 5 '17 at 0:57

You must log in to answer this question.

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