为什么我的第一个if语句被跳过而不接受C中的输入?

时间:2014-11-09 19:50:34

标签: c macos if-statement sleep scanf

代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int input;
system("clear");
printf("Welcome to Riddles! A game of mystery. Press any key and the enter button to continue.\n");
scanf("%d", &input);

system("clear");
sleep(1);
printf("Riddle 1. At night they come without being told. By day they are gone without being stolen. What are they?\n");
printf("1. goats\n");
printf("2. pillows\n");
printf("3. memories\n");
printf("4. the stars\n");
scanf("%d", input);

if (input == 1)
{
    system("clear");
    sleep(1);
    printf("Correct. The stars is the answer\n");
}

if (input != 1)
{
    sleep(1);
    system("clear");
    printf("Incorrect Game over\n");
}

}

问题:输出将打印:欢迎来到谜语!一场神秘的游戏。按任意键和输入按钮继续“就像它应该的那样,但当我输入一个字母然后按回车键时,这将出现:

谜语1.晚上他们没有被告知。白天他们走了,没有被偷走。这些是什么? 山羊 枕头 记忆 4.星星

游戏错误

问题是,我甚至无法输入答案。它会跳到第二个if语句而不接受任何输入。有谁知道问题可能是什么?

(p.s。我从北方的指环王战争中得到了这个谜语)

2 个答案:

答案 0 :(得分:2)

本声明中有一个拼写错误

scanf("%d", input);

应该

scanf("%d", &input);

此外,您不能为int类型的对象输入字母。因此,改变第一个scanf,以便输入一个字母。

答案 1 :(得分:0)

第二个if语句应该是else:

if (input == 1)
{
    system("clear");
    sleep(1);
    printf("Correct. The stars is the answer\n");
}

else //else statement instead of the 2nd if statement 
{
    (input != 1)
    sleep(1);
    system("clear");
    printf("Incorrect Game over\n");
}