我正在構建一個需要在if/else語句中使用典型「y/n」字符函數的長程序,它工作正常,但如果用戶放入某些無效的東西,它會重複我的「無效答案」字符串,等於他們放入的字符數。我嘗試了「%1s」而不是%c,但這並不能阻止失控輸入。如何停止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); while(* ansr!='y'&& * ansr!='n'){' – BLUEPIXY
使用:'char ansr; 012fscanf(「%1s」,&ansr);'錯誤;'%1s'需要一個指向2個字符的指針,一個用於字符,另一個用於字符串末尾的空值。 (「%c」,&answer)== 1){... OK ...} else {... EOF or error ...}'注意格式字符串中的前導空格,並且沒有尾部空格或空白字符;兩者都很重要 –