Kuba Srna
Kuba Srna

Reputation: 15

How to check scanf two integers in c

I have a problem, that I need to scan two integers in one line divided by a space, so the code looks something like this:

scanf("%d %d",&integer1,&integer2);

And in this code I need to check whether there were scanned two integers. Can someone help me? Thank you in advance

Upvotes: 1

Views: 4076

Answers (1)

Embedded C
Embedded C

Reputation: 1464

By default scanf() reads the space there is no meaning in giving space. If you want to read two integers scanf("%d %d",&integer1,&integer2); and scanf("%d%d",&integer1,&integer2); both will help you.

It will accept the following inputs:

1 2
12 22
3 2 5 //EOF

your program will pass only after reading two integers. You don't need to check anything.

To eliminate EOF

By default scanf returns number of values read so make use of it.

if(scanf("%d%d",&integer1,&integer2) != 2)
{
   //if more than two values are entered
   //perform some error handling
}

Upvotes: 1

Related Questions