c - scanf inside while loop working only one time -


so have code, supposed coordinates 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 know, should keep taking coordinates user, instead takes once, , crush in weird way, it's skipping scanf without reason. here's 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 confused, since simple code, , don't have slightes idea whats causing this. anybody?(if makes difference, system mountain lion)

one possible solution add space skip whitespace:

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

as user "undefined behavior" pointed out, should check return value. in case expect return value equal number of items reading, if return value <0 can't read stdin anymore , return value less number of items reading in indicates have conversion error.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -