Sneek Sneek - 2 months ago 7
C Question

Why doesn't the first letter of my string print?

I'm trying to write a piece of code that asks for user input to type in their name. It's then supposed to read each character of their name and format it however I choose (in the code below, it adds a new line after each character).

The problem I'm having is when someone types in their name, it doesn't print the first letter but prints out the rest.

For example, if I were to type in Sneek, it only displays neek.

Now I'm a beginner at programming and even more so with C so I was wondering if there is a problem with my scanf statement or the loop.

Also, if i type in Sneek it displays neek but if I type in Sneek again, it displays it as Sneek so I'm assuming theres nothing wrong with the loop?

I've searched for quite a while on this issue but I can't seem to find any answers, any help would be much appreciated.

char ch;
printf("Please enter name: ");
ch = scanf("%c", &ch);

while ((ch = getchar()) != EOF) {
printf("%c\n", ch);

}
return 0;

Answer

There are multiple issues in the code fragment:

  • The ch = scanf("%c", &ch); serves no purpose and does not even properly read a byte from the file into ch. Just remove this line.

  • while ((ch = getchar()) != EOF) { printf("%c\n", ch); } is correct for your purpose but the type of ch must be int instead of char to accommodate all values of unsigned char and the special value EOF. As currenly written, your code will fail to stop at end of file on platforms where char is an unsigned type.