5

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?

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

2 Answers2

11

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.

Community
  • 1
  • 1
Chris Cooper
  • 17,276
  • 9
  • 52
  • 70
4

scanf returns the number of items successfully read. You can check if it failed by checking against 1, because you're reading one item:

if (scanf("%d", &data) != 1)
    // error
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249