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

浪尽此生 提交于 2019-12-23 15:25:45

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/8186115/how-can-i-determine-if-scanf-read-what-was-specified-in-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!