+ 2

Why does my code skips a statement

I am new to C and I am attempting a program where it continuously ask for the user's name. However, although the program works it skips the first statement. Desired code: Output: Enter name: User Input: <name> Output: Your name is <name>. Do you want to add another name? User input: yes (starts all over) Current code: Output: Enter name: User Input: <name> Output: Your name is <name>. Do you want to add another name? User input: yes Output: Your name is. Do you want to add another name? (Ps. "Enter name" wont display) This is my code: ````` #include <stdio.h> int main() { char name[20], answer[5]; do{ printf("Name: "); fgets(name, 20, stdin); printf("Your name is %s", name); printf("Do you want to add another name? "); scanf("%s", answer); } while (strcmp(answer, "yes")==0); return 0; } ``````````

7th Mar 2024, 7:54 AM
Jade Tito
Jade Tito - avatar
2 Réponses
+ 5
scanf() does not handle the character that was read past the input for <answer> string. This character normally represent Enter key (on the keyboard) that we press after typing something at the input prompt to submit the input. The character is stranded in the input stream, and it was mistakenly taken as a blank line by fgets() the next time it tries to read input for <name> string. You can try flushing the input stream after using scanf() to read input for <answer>. I would also recommend you to set a limit for the size of <answer> input to avoid buffer overrun. scanf( "%4s", answer ); // limit input to 4 characters fflush( stdin ); // flush input stream Alternatively, you can tell scanf() to discard the one character representing Enter key by specifying asterix sub specifier. In my phone this approach works. And with this approach there seems to be no need to flush the input stream afterwards. You might wanna test it first on your machine to be confirmed though. scanf( "%4s%*c", answer ); // limit input size and ignore one last character
7th Mar 2024, 4:43 PM
Ipang
+ 3
since you are already using scanf, why not also just use it for name? mixing fgets and scanf in a while loop is not a good idea...
7th Mar 2024, 10:28 AM
Bob_Li
Bob_Li - avatar