char theInput[10];
long option;
int innerLoop = 1;
char *dunno;
while(innerLoop == 1){
printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: ");
fgets(theInput, sizeof theInput, stdin);
option = strtol(theInput, &dunno, 10);
if(option == 1){
loop = 0;
innerLoop = 0;
}else if(option == 2){
loop = 1;
outerLoop = 1;
innerLoop = 0;
firstLoop = 0;
}else if(option == 3){
loop = 1;
innerLoop = 0;
outerLoop = 1;
firstLoop = 1;
}else{
printf("\nInvalid input, please try again.\n");
innerLoop = 1;
}
}
此代码的结果是,首次运行时,它会打印"类型' 1'获得"部分后跟一个换行符后跟"输入无效,请再试一次。"不从命令行获取任何输入。然后它再次打印第一个printf语句,然后接受输入并工作。它打算打印第一个语句,然后等待输入。
以下是终端输出。
"输入' 1'为了得到你的改变,' 2'选择另一个项目,或者' 3'增加更多资金: 输入无效,请重试。
键入' 1'为了得到你的改变,' 2'选择另一个项目,或者' 3'增加更多资金:"
答案 0 :(得分:0)
你能尝试冲洗标准输出吗?
如果其他人想要一个有效的例子,我已经添加了主要方法:
#include <stdio.h>
int main () {
int loop = 0;
int outerLoop = 0;
int firstLoop = 0;
char theInput[10];
long option;
int innerLoop = 1;
char *dunno;
while(innerLoop == 1){
printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: ");
fflush(stdout);
fgets(theInput, sizeof theInput, stdin);
option = strtol(theInput, &dunno, 10);
if(option == 1) {
loop = 0;
innerLoop = 0;
}else if(option == 2){
loop = 1;
outerLoop = 1;
innerLoop = 0;
firstLoop = 0;
}else if(option == 3){
loop = 1;
innerLoop = 0;
outerLoop = 1;
firstLoop = 1;
}else{
printf("\nInvalid input, please try again.\n");
innerLoop = 1;
}
}
}
在调整源代码之前,您是否可以尝试在isoltion中运行此示例并查看是否有预期的结果?