我正在if / else语句中构建一个需要典型“y / n”char函数的长程序,它工作正常但是如果用户输入的内容无效,它将重复我的“Invalid answer”字符串等于他们输入的字符数。我尝试使用“%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;
}
答案 0 :(得分:1)
首先,您不希望将html1.html
与html2.html
一起使用,因为此格式说明符需要数组。在%1s
的内存位置写入1个字符后,它将在下一个内存位置写入一个空字节。这导致了未定义的行为。坚持使用char
。
要清除多余的字符,您希望在循环中使用ansr
来读取字符,直到找到换行符。这将刷新缓冲区。
%c
输出:
getchar
答案 1 :(得分:0)
要处理输入中的字符串,您可以尝试从stdin读取到ansr
缓冲区,如下所示,然后进行字符串比较。通过使用stdin
丢弃%*[^\n]
中剩余的内容,扫描不会受到空格或多个字符的影响,并且您可以获得所需的y/n
字符。另外,不要忘记你的右大括号,并在main
中返回零。
#include <stdio.h>
#include <string.h>
#define buffLen 32
int main() {
char ansr[buffLen] = "";
printf("...would you like me to predict your future? (y/n) \n");
while (strcmp(ansr, "y") != 0 && strcmp(ansr, "n") != 0){
// Read the string, and throw away the rest up to the newline char.
scanf("%s%*[^\n]", &ansr);
if (strcmp(ansr, "y") == 0) {
printf("You've been warned.\n");
} else if (strcmp(ansr, "n") == 0) {
printf("Goodbye Then.\n");
} else {
printf("Invalid answer, Please try again.\n");
}
}
return 0;
}
编辑:评论中有一个很好的建议是使用do-while循环来保存我们用虚拟内容初始化缓冲区ansr
,因为{{1} }} block在评估条件之前初始化缓冲区。我喜欢这个,因为我很少想到使用这些,但这是何时使用它的一个很好的例子......
do