How to determine if scanf read what was specified in the format?

I have a program that defines an int data variable

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

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

He did not work for me. So, how can I tell if scanf crashes or fails?

+4
source share
2 answers

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

eg.

 int items_read = scanf("%d", &data); if (items_read != 1) { //It was not a proper integer } 

There is a lot of discussion about reading integers here when stack overflows .

+8
source

scanf returns the number of items successfully read. You can check if this failed by checking against 1, because you are reading one element:

 if (scanf("%d", &data) != 1) // error 
+3
source

Source: https://habr.com/ru/post/1381935/


All Articles