首页 > 解决方案 > 试图创建一个猜测我的字母代码。如何合并用户输入的字符等于我的字母的情况?

问题描述

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

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

解决方案


读取单个字符的正确格式运算符是%c, not %1s。后者读取单个字符,但将其写入以空字符结尾的字符串,因此它将在userLetter变量外部写入空字节,这会导致未定义的行为。

您应该在操作符之前放置一个空格,以便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");
}

推荐阅读