Why 2nd scanf doesn't work in my program?

前端 未结 3 777
孤街浪徒
孤街浪徒 2020-12-11 05:09

scanf(\"%d %c\",&size,&chara); works but separate scanf for character input does not work. I show these inside the code. Why is that?

void squareCust         


        
相关标签:
3条回答
  • Yes I believe Armin is correct. scanf will read in whitespace (spacebar, newline, etc.). When you're inputting values if you click the space bar or enter right after the first scanf, the second scanf will read in that value (space, newline, etc.). So you fixed that with scanf("%d %c",&size,&chara) because there is a space between %d and %c. If you want them separate just do what Armin suggested: scanf(" %c",&chara).

    0 讨论(0)
  • 2020-12-11 05:56

    Scanf did not consume the \n character that stayed in the buffer from the first scanf call.

    So the second scanf call did.

    You have to clear the stdin before reading again or just get rid of the newline.

    The second call should be

    scanf(" %c",&chara);
           ^ this space this will read whitespace charaters( what newline also is) until it finds a single char
    
    0 讨论(0)
  • 2020-12-11 05:59

    Throw a getchar() in between them and slurp up that extraneous newline.

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