我正在尝试创建一个程序,将用户输入的字母与我的字母进行比较。如果字母相同,程序应该说它们是相同的,然后终止。如果它们不相同,则应该提示用户输入另一个字符,直到他们猜对为止。
我尝试过嵌套一个if语句和一个while循环来实现字母相等的情况。
#include <stdio.h>
int main()
{
char myLetter = 'a';
printf("insert a char:");
char userLetter;
scanf("%1s", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf("%1s", &userLetter);
}
while (userLetter == myLetter)
{
printf("char matches! program will terminate now. ");
break;
}
}
期望值:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
char matches! program will terminate now.
实际:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
a does not match mine, try again:a does not match mine, try again:^C
发布于 2019-04-16 21:17:00
读取单个字符的正确格式操作符是%c
,而不是%1s
。后者读取单个字符,但将其写入以null结尾的字符串,因此它将在userLetter
变量外部写入一个null字节,这会导致未定义的行为。
您应该在运算符之前放置一个空格,以便scanf
在读取字符之前跳过空格。这是为了让它在每次响应后忽略换行符。
您还应该关闭输出缓冲或在每次提示后刷新缓冲区,因为它们不会以换行符结束。
不需要在最后执行while
循环,因为直到字符匹配时才能退出第一个循环。
这是一个工作版本:
#include <stdio.h>
int main()
{
char myLetter = 'a';
setbuf(stdout, NULL);
printf("insert a char:");
char userLetter;
scanf(" %c", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf(" %c", &userLetter);
}
printf("char matches! program will terminate now.\n");
}
发布于 2019-04-16 21:22:39
如果你正在比较2个字符,为什么你不用scanf("%c", userLetter)
得到用户字母,然后你可以用=
或!=
运算符来比较它们。如果你希望得到一个字符串值的输入,那么我建议你这样声明userLetter
:
char* userLetter[1];
然后使用scanf,就像你在代码中做的那样,但是你必须用strcmp
函数比较字符串。
https://stackoverflow.com/questions/55716162
复制相似问题