0

My code has a problem with output. It prints only two simbol. And second simbol it's not correct

string s = GetString();

printf("%c", toupper(s[0]));

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

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

i++;
}
1

I see at least two problems. First, why do you increment i at the end of this code? The for loop setup does it already. If you were doing it to skip forward a letter after printing one, it should have been inside the if code block with the printf statement. Even then, it's not necessary.

Second, what happens if s[i] happens to be the character just before \0? Are you going to print the end of string marker? But then again, think about this. Does it matter?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

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

since you took care of s[0] separately (before the loop), do you think you still need to start with
i = 0?

if (s[i] == ' ' && s[i] != '\0')

let's agree that a char variable can hold one value and only one value. in the expression s[i] == ' ' && s[i] != '\0', if s[i] == ' ' evaluates to true, the whole expression evaluates to true (see why?). if s[i] == ' ' evaluates to false, the whole expression evaluates to false (see why?). that means that the && s[i] != '\0' is redundant and that makes sense actually given the first sentence in this paragraph — if s[i] holds a space, that means that it naturally doesn't hold a '\0'.

lastly, you are incrementing i twice which may skip some characters.

You must log in to answer this question.

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