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,250
  • 13
  • 64
  • 126
Yakov
  • 9,221
  • 29
  • 109
  • 199

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
  • 16,826
  • 9
  • 51
  • 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
  • 72,057
  • 21
  • 174
  • 247