这个function运行太多次了
为什么我写了一些其他字母或数字(不是y \ n)的订单
printf("\nWould you like to play again? (y/n):");
跑了两次?
int ans= 0,i=1; do { printf("\nWould you like to play again? (y/n):"); ans = getchar(); if (ans=='y') { printf("yyyyyyyyyyy"); i = i-1; } else if ( ans == 'n') { printf("nnnnnnnnnnn"); i=i-1; } else { printf("not y or n"); } } while(i);
while(i)
实际上与while(i != 0)
。 如果输入y
或n
,则else
块会运行,并且不会更改i
的值。 由于在循环之前i=1
,如果输入除y
或n
之外的其他内容,则i
为非零。 尝试:
else { printf("not y or n"); i = i-1; // <---- new line }
可能是因为你的getchar
调用正在从输入中获取换行符。 因此,如果你按’X’,第一次通过循环ans
是’X’并且换行被缓冲。 第二次通过循环ans
是’\ n’。
您可以像这样在输入调用周围循环:
do ans = getchar(); while (isspace(ans));
这太复杂了。 正如您在评论中所述,您只想循环直到输入y
或no
。 不需要额外的变量。 一般来说,对于这些问题,使用计数器是个坏主意。 更多故障安全是使用bool
标志。
没有辅助变量的好方法是:
int ans; // no need to initialise, as it is set before the first read do { printf("Play again?"); do { ans = getchar(); } while ( ans == `\n` ); ... } while ( (ans != EOF) && !strchr("yYnN", ans) );
见strchr
。 我添加了对大写字母的容忍度。
请注意,您也始终检查EOF。 因为它不能表示为char
,所以必须单独测试并首先测试(否则strchr
的转换可能会产生意外结果。
另请注意,输入流(可在Internet上的某些代码中找到)是未定义的行为 – 请勿使用它。 即使某些库容忍它,它们也可能不会按预期运行(这是未定义的行为所暗示的)。 一般刷新为“写/发送”数据的语义。 输入通常是“丢弃”(并且没有fdrop
function。
编辑:添加内部循环以删除换行符。 如果没有这个,循环将在输入无效字符后运行两次。 这假设您必须每行输入一个字符。
无论你输入什么字母,然后按Enter键 ,该行
c = getchar();
仍然在输入流中留下换行符。
如果该字符不是y
和n
,则在不等待您的情况下执行该调用,并将换行符分配给c
。 因此,您会看到以下两行的输出。
printf("\nWould you like to play again? (y/n):");
和
printf("not y or n");
您需要添加代码以忽略输入后的其余行
c = getchar();
添加function:
void ignoreRestOfLine() { int c; while ( (c = getchar()) != EOF && c != '\n'); }
并称之为:
c = getchar(); ignoreRestOfLine();
另一种方案:
char c = 'x'; // Initialize to a character other than input while( c != 'y' || c != 'n') { // You can also use strchr as @Olaf mentioned printf ("\nPlay again (y/n): "); c = getchar (); }
问题是当你再次进入程序时,内存中已有答案。 getchar()
添加一个\ n,这就是getchar()
东西。 为了避免这种情况,你可以使ans成为一个字符(char),这意味着它将读取ascii表; (y = 121和n = 110)。 收到输入后,Char不会放置\ n(新行),以确保发生这种情况,你必须在%c之前留一个空格,如scanf(" %c", &ans);
这意味着ans正在接收一个int。
#include #include int main(void){ char ans; int i = 1; do { printf("\nWould you like to play again? (y/n):"); scanf(" %c", &ans); if (ans == 121){ printf("yyyyyyyyyyy"); i = i - 1; } else if ( ans == 110){ printf("nnnnnnnnnnn"); i = i - 1; } else{ printf("not y or n"); } } while(i); }