c - IF 语句不能正常工作

标签 c if-statement

我决定制作一个玩井字游戏的程序,但我用 if 语句失败了。它使用了我放在 else 下的任何内容。我已经盯着它看了两个小时了,我就是找不到任何不对劲的地方!这是代码:

#include <stdio.h>
#include <process.h>

int main()
{
char ans,ans2;
double a,b,c,d,e,f;
printf("Do you want to play? (y/n)\n"); //must make a loop
scanf ("%c",&ans);
if (ans == 'y')
{
    printf("Do you want to be first?\n");
    scanf ("%c",&ans2);
    if (ans2 == 'y')
    {
        printf("Make your choice.\n");
        printf(" 1 2 3\n");
        printf("a | | \n");
        printf(" - - -\n");
        printf("b | | \n");
        printf(" - - -\n");
        printf("c | | \n");
    }
    else if (ans2 == 'n')
    {
        printf("option under construction!\n"); //must write this situation
    }
    else
        printf("Invalid choice!\n");
}
else if (ans == 'n')
{
    printf("Goodbye!\n");
    system("pause");
}
else
    printf("Invalid choice!\n");

}

请注意,该程序还没有完成(很明显)。

附言我昨天开始编程。

最佳答案

我猜,问题在于,当您使用 scanf 读取一个字符时,它会读取该字符,但您还输入了换行符。下一个 scanf 调用将读取该换行符而不是预期的字符。

最简单的解决方案是告诉 scanf 跳过空格(如换行符):

scanf(" %c", &ans);

注意 %c 之前的空格。

关于c - IF 语句不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15615798/

相关文章:

c++ - 如何在输入 '#' 时禁用建议

c - 如何在 C 中将 setitimer 与 SIGALRM 一起使用

c - 有没有办法写得更简洁?

java - 不会写入文件?

regex - 批处理 - 将变量与正则表达式进行比较

C - 程序正在编译,但无法提供参数

c - 查找 C 代码段的运行时间

mysql - 在mysql查询中设置条件

java - if语句只检查一次

c++ - 奇怪的 if 语句导致关闭计时器