"ferror" 测试 "scanf" 输入
"ferror" tests "scanf" input
我试图在下一个程序中输入错误数据,但无法识别错误。一次我输入数字数据,下一次输入字符串数据,但程序没有反应:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main(void)
{
int i;
scanf("%d",&i);
if(ferror(stdin))
printf("Error is ocurred!");
}
不要假设函数的作用。阅读它的文档。
https://www.cplusplus.com/reference/cstdio/ferror/
int ferror ( FILE * stream );
Check error indicator
Checks if the error indicator associated with stream is set, returning a value different from zero if it is.
This indicator is generally set by a previous operation on the stream that failed, and is cleared by a call to clearerr, rewind or freopen.
所以这取决于 scanf
是否设置了错误指示器,在这种情况下它没有设置。
改为使用:
if(scanf("%d",&i) != 1) {
// Error code
哦,不要使用 use namespace std
Why is "using namespace std;" considered bad practice?
我试图在下一个程序中输入错误数据,但无法识别错误。一次我输入数字数据,下一次输入字符串数据,但程序没有反应:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main(void)
{
int i;
scanf("%d",&i);
if(ferror(stdin))
printf("Error is ocurred!");
}
不要假设函数的作用。阅读它的文档。
https://www.cplusplus.com/reference/cstdio/ferror/
int ferror ( FILE * stream );
Check error indicator
Checks if the error indicator associated with stream is set, returning a value different from zero if it is.
This indicator is generally set by a previous operation on the stream that failed, and is cleared by a call to clearerr, rewind or freopen.
所以这取决于 scanf
是否设置了错误指示器,在这种情况下它没有设置。
改为使用:
if(scanf("%d",&i) != 1) {
// Error code
哦,不要使用 use namespace std
Why is "using namespace std;" considered bad practice?