-2

Code:

#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");
}

}

Problem: The output will print :Welcome to Riddles! A game of mystery. Press any key and the enter button to continue" just like it should but when I type in a letter and press enter, this will come up:

Riddle 1. At night they come without being told. By day they are gone without being stolen. What are they? 1. goats 2. pillows 3. memories 4. the stars

Incorrect Game over

The problem is, I couldn't even type an answer. It would skip to the second if statement without accepting any input. Does anyone know what the problem could be?

(p.s. I got this riddle from Lord of the Rings War in the North)

Ryan
  • 31
  • 2
  • possible duplicate of [Scanf skips every other while loop in C](http://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c) – indiv Nov 09 '14 at 19:54
  • Scanning a letter using %d ? – Gopi Nov 09 '14 at 19:57
  • Stars or goats ? (Stargåte?) –  Nov 09 '14 at 20:03
  • @indiv Not a dupe as cited as that one deals with problems with `scanf("%c")` and this one incorrectly uses `scanf("%d")`. Likely a dupe of some other post – chux - Reinstate Monica Nov 10 '14 at 04:50
  • @Ryan Why do you think `scanf("%d", &input);` is a good idea to read letters? Subsequent `scanf("%d", &input);` are all trying to read the same letter and they _all_ fail. Lesson: check the results of `scanf()`, when it is 0, it may mean input is still not consumed. – chux - Reinstate Monica Nov 10 '14 at 04:53

2 Answers2

2

There is a typo in this statement

scanf("%d", input);

Shall be

scanf("%d", &input);

Also you may not enter a letter for an object of type int. So change the first scanf such a way that you could enter a letter.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

the second if statement should be an 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");
}