【发布时间】:2016-04-26 23:57:44
【问题描述】:
我正在构建一个长程序,需要在 if/else 语句中使用典型的“y/n”字符函数,它工作正常,但如果用户输入无效的内容,它将重复我的“无效答案”字符串等于他们输入的字符数。我尝试使用“%1s”而不是 %c,但这并不能阻止失控输入。
#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'){ -
使用:
char ansr; scanf("%1s", &ansr);是错误的;%1s需要一个指向 2 个字符的指针,一个用于字符,一个用于字符串末尾的 null。也许你想要char answer; if (scanf(" %c", &answer) == 1) { …OK… } else { …EOF or error… }。注意格式字符串中的前导空格,并且没有尾随空格或空格;两者都很重要。