Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 577
Leo Avatar asked Dec 04 '25 10:12

Leo


2 Answers

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.

like image 87
Shafik Yaghmour Avatar answered Dec 07 '25 01:12

Shafik Yaghmour


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

like image 35
Lakshman Diwaakar Avatar answered Dec 07 '25 00:12

Lakshman Diwaakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!