提问人:Grolldash 提问时间:11/20/2022 最后编辑:Andreas WenzelGrolldash 更新时间:11/20/2022 访问量:59
在 C 语言中使用 scanf 的多个条件
Multiple conditions with scanf in C
问:
TLDR:在使用 EOF 时,我需要检查我使用 scanf 扫描到数组中的输入是否真的是整数。
我需要将数字扫描到数组中,直到 EOF。我使用静态分配的内存做所有事情,因为我是一个初学者,现在动态分配的内存对我来说很难理解。我也使用 getc 在末尾获取“\n”输入(但这不是问题 - 只是这样说,所以你知道)。我的第一个想法是:
while(scanf("%d", &number[i][j]) != EOF )
**some code**
但此解决方案不会检查输入是否为整数。例如,如果我的输入是。
1 2 3
4 0 5
2 3 a
代码不会停止,因为最后一个数组的值是 0,直到我扫描一个数字进入其中。我的解决方案是
while(1)
if(scanf("%d", &number[i][j]) != 1)
printf("Incorrect input.\n");
return 0;
但由于 EOF 等于 -1,这意味着我甚至在我不想要的文件末尾也得到了输入。那么有没有办法让更多的条件比较扫描呢?例如(我知道这行不通,但为了帮助您理解我的意思):
while(1)
if(scanf("%d", &number[i,j] != 1 && scanf("%d", &number[i,j]) != EOF)
printf("Incorrect input.\n");
return 0;
但是这个“解决方案”需要两次输入。我还在这个网站上找到了一些答案,建议使用其他方式代替 scanf,但我需要专门使用 scanf 函数。
答:
1赞
Andreas Wenzel
11/20/2022
#1
您可以将返回值保存到类型的变量中,然后稍后对其执行进一步的测试:scanf
int
int val, ret;
while ( ( ret = scanf( "%d", &val ) ) != EOF )
{
if ( ret != 1 )
{
printf( "Incorrect input.\n" );
exit( EXIT_FAILURE );
}
//input is ok, so do something with the input value
DoSomethingWithValue( val );
}
//if this line of code is reached, then EOF has been encountered
评论
while( 1 == scanf(...))
feof
while( (c = scanf(...)) == 1){...} if( c == 0) { /* report bad input and abort */ } else { /* hurrah, EOF without input error */}
{}
number[i,j]