Leo
Leo

Reputation: 2103

scanf inside while loop working only one time

so i have this code, which is supposed to get coordinates from user:

#include <stdio.h>
#include <time.h>

int main() {
int number;
char letter;
int points = 3;
    while(points < 8){
        printf("give me first coordinate (letter)");
        scanf("%c",&letter);
        printf("give me second coordinate (number)");
        scanf("%d",&number);
    }
}

as far as i know, this should keep taking coordinates from a user, but instead it takes it only once, and then crush in a really weird way, like it's skipping scanf without any reason. here's my output:

give me first coordinate (letter)a
give me second coordinate (number)1
give me first coordinate (letter)give me second coordinate (number)12
give me first coordinate (letter)give me second coordinate (number)df
give me first coordinate (letter)give me second coordinate (number)give me first coordinate (letter)give me second coordinate (number)sss

I feel really confused, since this is simple code, and i don't have the slightes idea whats causing this. anybody?(if it makes any difference, my system is mountain lion)

Upvotes: 2

Views: 9871

Answers (3)

Lakshman Diwaakar
Lakshman Diwaakar

Reputation: 7569

scanf(" %c",&ch);

The reason this works is that the first space flushes stdin and then lets the user input the character.

this also works if you put /n or /t before %c

Upvotes: 4

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158449

One possible solution is to add a space to skip whitespace:

scanf(" %c",&letter);
       ^

As user "undefined behavior" properly pointed out, you should also check the return value. In this case you expect the return value to be equal to the number of items you are reading, if the return value <0 then you can't read from stdin anymore and a return value less than the number of items you are reading in indicates you have a conversion error.

Upvotes: 8

V-X
V-X

Reputation: 3029

I personally don't like usage of scanf. This function leaves the input stream in not so well defined state as it would look. I prefer fgets combined with sscanf...

Upvotes: -1

Related Questions