tags:

views:

699

answers:

5

I am using scanf() to get a set of ints from the user. But I would like the user to supply all 4 ints at once instead of 4 different promps. I know I can get one value by doing:

scanf( "%i", &minx);

But I would like the user to be able to do something like:

Enter Four Ints: 123 234 345 456

Is it possible to do this?

+8  A: 

You can do this with a single call, like so:

scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);
Reed Copsey
According to my man page, it's %d not %i
wrang-wrang
p.s. nice choice of variable names :)
wrang-wrang
you can use %d %i %o %x %X for ints.. http://montcs.bloomu.edu/~bobmon/Information/LowLevel-Programming/printf-formatting.shtml
Josh Curren
%d is almost identical to %i. They do the same thing in most cases.
Chris Lutz
@Chris: under what circumstance does %i not do what %d does?
Jonathan Leffler
@Jonathan Leffer - According to my scanf manpage, "%i" reads the int in base 16 if it begins with `0x` and in base 8 if it begins with `0` and base 10 otherwise. "%d" reads in base 10 always. And the Open Group manpage agrees with mine.
Chris Lutz
Cool. Will %i work on all of windows/*bsd/linux/macosx?
wrang-wrang
@wrang-wrang: Yes, it should. Normally, if you'd use a %d, though, unless you expect non-base 10 numeric data entry.
Reed Copsey
+5  A: 

Yes.

int minx, miny, maxx,maxy;
do {
   printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);

The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).

wrang-wrang
The only trouble with that code is that if the user enters just 1 value, then they have to re-enter all 4 values on the next cycle.
Jonathan Leffler
Agreed - but it serves them right :)
wrang-wrang
+1  A: 
int a,b,c,d;
if(scanf("%d %d %d %d",&a,&b,&c,&d) == 4) {
   //read the 4 integers
} else {
   puts("Error. Please supply 4 integers");
}
nos
A: 

Could do this, but then the user has to separate the numbers by a space:

#include "stdio.h"

int main()
{
    int minx, x, y, z;

    printf("Enter four ints: ");
    scanf( "%i %i %i %i", &minx, &x, &y, &z);

    printf("You wrote: %i %i %i %i", minx, x, y, z);
}
l3dx
A: 

how many scans can u have in a row? i used 5 scans and it gives me a syntax error is that the case? can i use more than 4 scans in a line?

meir