1

everyone! I have one problem with code initials. It correctly runs but after check50 I've got some issues , among them- ***\ expected output, but not " \u0000\n"***that I can't fix.Help me,please)

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

int main (void)
{

    string n=get_string();
    printf("%c",toupper(n[0]));

    for(int i=1,l=strlen(n);i<l;i++)
    {
        if(isspace(n[i]))
        { 
           printf("%c",toupper(n[i+1]));
           i++;
        }
    }

    printf("\n");
    return 0;
}
3

There are a few errors in your code that mess up your output.

printf("%c",toupper(n[0])); has a serious error. This works for Robert Thompson but not if there was a space before Robert. It would count the space as the initial and print it out, which will cause check50 to give errors. You want the first alphabetical letter, not the first character. There are many ways you could check for spaces before the string, but I'll leave it to you to find the solution.

if(isspace(n[i])) also has a serious error. You are checking for a space and then using the character after that space (which you assume is an alphabetical letter) as the initial. But, how do you know that the next letter/character is an alphabetical letter? Let's say we inputted John Doe with 2 spaces in front of it. You hit if(isspace(n[i])) on the first iteration of the loop. Is the first character a space? In this case, yes, so the code in your if statement executes and - instead of printing J - prints a space. In the end, we get a space and JD when we just want the initials JD. Instead of just checking if the character is a space, also check if the character after it is not a space. That way, you don't print out extra spaces in your code.

In addition, how do you know that n[i + 1] is not the end of the string (\0)? You might want to check for that before you print out the character.

Another error arises at i++. In a for-loop, the variable automatically increments with each iteration. i = 1, i = 2, etc. However, adding this extra i++ will increment i twice. i = 1, i = 3, etc. This causes you to skip letters in your string, so you don't output all the letters you need to.

Hopefully this will push you in the right direction to help you find out the solution to your other errors. If you still have issues, comment below.

2
  • This comment is a life saver. Thanks so much! I've been stuck with printing extra spaces and i never did u[i+1] != ' '. Feb 24 '17 at 0:08
  • I'm glad it helped you! Feb 24 '17 at 16:57
0

Although everything CodeForTheStars says is true your program should work in the less comfortable version. The problem is in the for loop simply change by the following:

for(int i = 0 ,l = strlen(n); i < l; i++)

It's a good exercise to think about why.

You must log in to answer this question.

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