0

I'm new to programming and I have solved the less comfortable version of initials.c in pset2 but I'm having trouble with the output of more comfortable version of initials.c. Here's my code:

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

int main(void)

{
printf("Your name is: ");
string s = get_string();

if (s[0] != ' ')
{
    printf("%c", toupper(s[0]));
}

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

printf("\n");
}

When I execute the code, for " Zamyla Chan "

I get Z C

instead of

ZC

The number of spaces is exactly one less than total number of spaces between two separate words. Why is this happening? I am not able to figure out what is wrong with my code.

1 Answer 1

0

s[i+1] != 0 && s[i+1] != '\0' is actually twice the same ('\0' is an 8-bit integer of value 0). Maybe you meant something like s[i+1] != 0 && s[i+1] != ' ' instead?

2
  • Yes. Sorry. My code was correct but then, I guess i typed in 0 instead of ' ' but the idea was to add ' '. Now that I've added space, it's correct. Silly mistake. Thank you.
    – Tejesh Atr
    Jun 20, 2017 at 12:51
  • We've all made such stupid mistakes. Sometimes an additional pair of eyes helps :)
    – Blauelf
    Jun 20, 2017 at 12:58

You must log in to answer this question.

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