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

标签 c

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

我试过嵌套一个 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 变量之外写入一个空字节,这会导致未定义的行为。

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

关于c - 尝试创建一个猜测我的字母代码。如何合并用户输入的字符等于我的字母的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55716162/

相关文章:

c - 这个哈希函数是如何工作的?这些数字是随机的吗?

c - 如何使用 #define 创建树

c - 文件处理中的意外输出

c - 使用 void * 写入硬件寄存器

c++ - Visual Studio 和 GCC 中的参数传递

c - 在 Linux 中打印出 sleep 控制台

c - 从 void 指针复制到结构的错误数据

c - 简单的 makefile 不生成输出文件(正确)

C用户定义函数问题

C - 每当我遇到空格时,循环似乎减半