Re: a scanf() question



Thanks to all who replied! Special thanks to Simon: the trick with n <
10 && scanf("%d", &i) == 1 is great. Have a nice day ;)


Simon Biber wrote:
Mik0b0 wrote:
Good day to everyone,
I have trouble finding a solution to this problem: how to pick up 10
numbers
corresponding to certain criteria (-399>=number<=400) from the input?
The number of input numbers is not limited. Thanks!

#include <stdio.h>

int main(void)
{
int i,n;
for(n = 0;
n < 10 && scanf("%d", &i) == 1;
n += -399 <= i && i <= 400);
return 0;
}

Here's an example run:

C:\docs\prog\c>a
100
200
300
400
500
600
700
800
100
200
300
400
500
600
700
800
100
200

It ignored the 500, 600, 700 and 800 in the input, and continued taking
input until it had read 10 numbers in the correct range. Those were 100,
200, 300, 400, 100, 200, 300, 400, 100, 200.

--
Simon.

.



Relevant Pages

  • Re: tolower() and toupper()
    ... Simon Biber wrote: ... type, not char? ... int c1, c2; ... Chuck F (cbfalconer at maineline dot net) ...
    (comp.lang.c)
  • Re: why do strcpy, strcat, & co return a pointer ?
    ... Simon Biber wrote: ... >> That code has undefined behavior, ... >int main ... Rouben Rostamian ...
    (comp.lang.c)
  • Re: parsing a string
    ... Simon Biber wrote: ... YYYYMMDD from the following string. ... int main{ ...
    (comp.lang.c)
  • Re: short or int
    ... In article, Simon Biber ... Then why would one use an int instead of a short ... There is no reason to use one over the ... On the vast majority an int is 16 bits. ...
    (comp.lang.c)