Problems with scanf

前端 未结 4 1397
粉色の甜心
粉色の甜心 2020-12-20 09:05
#include 

int main()
{

    char C, B;
    int x;



    printf(\"What comes after G\\n\");
    scanf(\"%c\", &C);

    printf(\"What comes after         


        
相关标签:
4条回答
  • 2020-12-20 09:21

    You can use scanf to eat the single character without assigning it to anything like this::

    scanf( "%[^\n]%*c", &C ) ;
    

    %[^\n] tells the scanf to read every character that is not '\n'. That leaves the '\n' character in the input buffer, then the * (assignment suppression) will consume the a single character ('\n') but would not assign it to anything.

    0 讨论(0)
  • 2020-12-20 09:24

    The problem is you are using scanf to get the character ..and a new line will be added at the end of each input from user . So the second time only the new line will be stored in the 'B' Because of the first input given by you ..

    Instead of scanf , change it to getchar - your problem should get solved

    0 讨论(0)
  • 2020-12-20 09:35

    The reason for this problem is newline character \n leftover by the previous scanf after pressing Enter. This \n is left for the next call of scanf.
    To avoid this problem you need to place a space before %c specifier in your scanf.

    scanf(" %c", &C);  
    ...
    scanf(" %c", &B);
    ...
    scanf(" %c", &X);  
    

    A space before %c is able to eat up any number of newline characters.

    0 讨论(0)
  • 2020-12-20 09:38

    You need to eat up the white space (i.e. new line) - as per the manual page http://linux.die.net/man/3/scanf

    0 讨论(0)
提交回复
热议问题