-
sort of stuck
hi all
right now i got this code
if (scanf("%d %d", &year, &month)!=2) {
printf("Input error\n");
}
it sort of behaves how i wanted it to like when i didnt enter 2 integers will pop out input error
however if i enter 1 integer the program will be stuck and just appear normal until i enter something twice
how do i fix it so that it will print input error if i enter less than 2 integer?
thx
-
One obvious solution, if you expect the user to input all the data on one line is to use a text input, and then "parse" the text input for the relevant data. For example:
Code:
char buffer[20];
...
if (fgets(buffer, sizeof buffer, stdin) != NULL || (sscanf(buffer, "%d %d", &year, &month)!=2) {
printf("Input error\n");
}
This will make sure that one line of data is input, and then try to translate it to year and month - and if either fails for some reason, it will produce "input error".
--
Mats
-
thx for the reply mats
but i think this fgets and buffer is way too complicated for this program (we are only allowed to use what we learn)
are there any other simpler methods?
-
Issue two scanf()'s, one for year, and the second for month.
-
thx for th reply todd but i dunno y it still doesnt work... if i enter a year but no month like XXXX -
(- means nothing) program wont appear normal until i enter something
the output of program will be like this
Enter year and month: 2008
1<---- random thing on keyboard
twenty hundred eight
has three hundred and sixty six (366) days
January has 31 days
Code:
if (scanf("%d", &year)!=1) {
printf("Input error\n");
}
if (scanf("%d", &month)!=1) {
printf("Input error\n");
}
-
So, if you use fgets(), it will read a line. It's not very complicated really, and there is no other (simple) solution that works.
--
Mats