[c] Getting multiple values with scanf()

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?

This question is related to c scanf

The answer is


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

scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);

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).


int a[1000] ;
for(int i = 0 ; i <= 3 , i++)
scanf("%d" , &a[i]) ;

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);
}

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");
}

Passable for getting multiple values with scanf()

int r,m,v,i,e,k;

scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);

Just to add, we can use array as well:

int i, array[4];
printf("Enter Four Ints: ");
for(i=0; i<4; i++) {
    scanf("%d", &array[i]);
}