Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if scanf read what was specified in format?

Tags:

c

integer

scanf

I have a program that defines a variable int data

The program uses scanf("%d",&data) to read data from stdin. If the data from stdin is not an integer, I have to print error message.

I tried if(scanf("%d",&data) ==EOF){ printf("error");return 1;}

It didn`t works for me. So, how can I determine if scanf failed or succeeded?

like image 393
Yakov Avatar asked Nov 18 '11 17:11

Yakov


1 Answers

scanf's return value is an integer, telling you how many items were succesfully read. If your single integer was read successfully, scanf will return 1.

e.g.

int items_read = scanf("%d", &data);

if (items_read != 1) {
    //It was not a proper integer
}

There is a great discussion on reading integers here, on Stack Overflow.

like image 194
Chris Cooper Avatar answered Oct 12 '22 23:10

Chris Cooper