我的程序跳过获取输入数据?

我写了一个简单的程序来兑换货币并且能够买到啤酒。

但是在程序中有一些东西,我不知道为什么,它会自动跳过第三个输入数据 – >结束程序。

这是我的代码:

#include  #include  int main() { int ex_rate_into_vnd = 20000; //! Exchange Rate int beer = 7000; //! Local price of a beer float in_c = 0; //! Input amount of money float out_c = 2; //! Amount of currency to exchange ! float choice; //! Switch mode char buy; //! Deal or not //! Introduction printf ("||---------------------------------------------------||\n"); printf ("|| Currency Exchange Machine beta ||\n"); printf ("||---------------------------------------------------||\n"); printf ("Please choose your option:\n"); printf("\t 1.Exchange VND to dollar\n"); printf("\t 2.Exchange Dollar to VND\n"); do { printf("Your choice: ",choice); scanf("%f",&choice); } while( choice != 1 && choice != 2); printf ("Please enter amount of money:"); scanf("%f",&in_c); if (choice == 1 ) { out_c = in_c / ex_rate_into_vnd; printf ("Your amount of money: %.2f",out_c); } else { out_c = in_c * ex_rate_into_vnd; printf ("Your amount of money: %.0f",out_c); } //! End of Exchanging printf ("\nWould you like to buy a beer (y/n) ?",buy); scanf("%c", &buy); if (buy == 'y') { if (out_c >= 7000) { out_c = out_c - 7000; printf("Transactions success !\n"); printf("Your amount: %2.f",out_c); } } printf ("\nWhy Stop ?"); return 0; } 

最新的float条目和要读取的char之间至少有一个\n 。 你需要先摆脱它。

另请参阅scanf类别后getchar所有答案

更改

 scanf("%c", &buy); 

 scanf(" %c", &buy); // ^space 

因为输入数字后换行符仍在输入缓冲区中,然后在第二个scanf按ENTER键。

而不是scanf("%c", &buy);

1.在%c之前使用空格

 scanf(" %c",&buy); //space before %c ^ 

这会跳过读取空白区域(包括换行符)。

2.or使用getchar(); 在scanf之前(“%c”,&buy); 声明

 getchar(); //this hold the newline scanf("%c", &buy); 

3.或者使用两次getchar();

 getchar(); buy=getchar(); //here getchar returns int , it would be better if you declare buy with integer type. 

在GCC中使用fflush(stdin); 是不鼓励的。 请避免使用它。

我想知道为什么你让’choice’成为一个浮点数,而不是一个int。另外,考虑使用这种方式的switch-case,你不必进行整个do-while循环。 另外,在行printf(“\ n你想买啤酒(y / n)?”, ); 你为什么加了? 这是我会做的:

 printf("Your choice?\n>"); scanf("%d", &choice); switch(choice) { case 1 : { out_c = in_c / ex_rate_into_vnd; printf ("Your amount of money: %.2f",out_c); } case 2: { out_c = in_c * ex_rate_into_vnd; printf ("Your amount of money: %.0f",out_c); } default : printf("\nThere has been an error\n"): reloadprogram(); /* Reloadprogram() is simply to make this go back to the asking thing :) */ } 

}

编辑:此外,它说if( >= 7000) ,将7000改为啤酒,这样,如果你改变啤酒,你将不必改变这个:)

在最后一次扫描之前放一个fflush(stdin)来清除输入

程序不会跳过第三个输入数据,只扫描第二个输入后按下的换行符。 要解决此问题,请键入scanf("%*c%c", &buy); 而不是scanf("%c", &buy); 。 这个小%*c扫描并忽略从输入读取的字符。

你可以从printf调用中删除buy变量,这是不需要的

 printf ("\nWould you like to buy a beer (y/n) ?",buy); 

并用char buy替换char buy char buy[2]; 。 因为sting总是被/0终止。

您还可以添加一个memset (buy, 0, sizeof(buy)) ,以确保在开始使用之前重置内存。