scanf ignoring, infinite loop

后端 未结 6 1017
遥遥无期
遥遥无期 2020-11-27 22:54
int flag = 0;
int price = 0;
while (flag==0)
{
    printf(\"\\nEnter Product price: \");
    scanf(\"%d\",&price);
    if (price==0) 
        printf(\"input not          


        
6条回答
  •  [愿得一人]
    2020-11-27 23:20

    After the first number, a '\n' will be in the input buffer (the return you pressed to input the number), so in the second iteration the scanf call will fail (becouse \n isn't a number), scanf will not remove that \n from the buffer, so in the next iteration it will fail again and so on.

    You can fix that by reading the '\n' with a getchar() call after scanf.

提交回复
热议问题