Search code examples
cfgetsgetchar

Program doesn't wait for the second read


This is a part of a bigger program, but what is driving me crazy is the fact that the program doesn't wait for something to be read from stdin in the string s (it just puts null in string s) , but if I put the read of the string s first and afterwards I read the character c the program works just fine. The thing is I need to read the data in this specific order. How can i fix it?

char s[100],c;
printf("enter character:\n");
c=getchar();
printf("enter string text:\n");
fgets(s,101,stdin);   
uint8_t s_len = strlen(s) - 1;        
s[s_len] = '\0'; 
printf("i have read %s\n",s);

Solution

  • When you press the enter key for the first character, the actual newline is still left in the input buffer. This newline is then read by the fgets call.

    You can solve this by a couple if different methods. The first is to add a dummy getchar call, to get the newline. This has the drawback that if you're on Windows that newline is actually two characters.

    Another solution is to use fgets for the first character as well, and then use e.g. sscanf to extract the character.