尝试创建一个猜测我的字母代码.我如何合并用户输入字符等于我的字母的情况



我正在尝试创建一个程序,将用户输入的字母与我的字母进行比较。如果字母相同,程序应说它们相同,然后终止。如果它们不同,则应提示用户输入另一个字符,直到他们猜对为止。

我尝试嵌套 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

读取单个字符的正确格式运算符是 %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");
}

如果您要比较 2 个字符,为什么不将用户字母与 scanf("%c", userLetter) 进行比较,然后您可以将它们与=!=运算符进行比较。如果您获得期望字符串值的输入,那么我建议您像这样声明userLetter

char* userLetter[1];

然后像在代码中那样使用 scanf,但您必须将字符串与strcmp函数进行比较。