私は典型的な "y/n" char関数をif/else文で必要とする長いプログラムを構築していますが、うまくいきますが、ユーザが何か無効なものを入れた場合、 "Invalid answer" %cの代わりに "%1s"を実行しようとしましたが、暴走入力を止めません。cのcharに対する繰り返しの無効な回答を停止する方法は?
#include<stdio.h>
int main()
{
printf("Welcome.I can predict the future\n"
"I learned this gift from someone in the future.\n"
"A bright creature with green eyes taught me how.\n"
"It appeared to me on a Sunday without enthusiam\n"
"and told me I would end up trapped in a computer,\n"
"and there was nothing I could do about it.\n"
"It was really cruel of it to do that.\n"
"I could have enjoyed the rest of my days\n"
"without being depressed having known that...\n"
"I also didn't need to know so many other things I\n"
"now have learned.\n\n"
"Having said this, would you like me to predict you\n"
"future?y/n\n");
char ansr;
scanf("%1s", &ansr);
while (ansr != 'y' && ansr != 'n'){
printf("Invalid answer, Please try again.");
scanf("%1s", &ansr);
}
if (ansr == 'y') {
printf("You've been warned.\n\n");
}
else if (ansr == 'n') {
printf("Goodbye Then.\n\n");
}
return 0;
}
'char ansr [2]; scanf( "%1s"、ansr); ながら(* ANSR = 'Y' && * ANSR = 'N'!){ '使用 – BLUEPIXY
:'チャーANSRと、 のscanf(「%の1」、&ansr);が '間違っている;'%の1s'は2つの文字、文字列の最後の文字用とヌルのための1つのポインタを必要とたぶんあなたは 'char型の答えを求めていました;。(scanfの場合( "%c"、&answer)== 1){... OK ...} else {... EOFまたはエラー...} 'フォーマット文字列の先頭の空白には空白または空白がなく、どちらも重要です。 –