如何输入eof(Ctrl + z),同时让scanf在说明符之前有一个空格以避免出现以前的\n错误?

How to input eof(Ctrl+z) while letting the scanf have a space before the specifier to avoid getting previous \n error?

提问人:Test Raw 提问时间:1/5/2021 最后编辑:BarmarTest Raw 更新时间:1/5/2021 访问量:126

问:

enter image description here

(我按回车键)

#include<stdio.h>
#include<stdlib.h>
int main(){
    int target,result;
    while(1){
        printf("Please input your target: ");
        scanf(" %d",&target);
        if(feof(stdin)){
            break;
        }
        printf("test\n");       
    }
}

如果我将代码更改为:(删除空格)

#include<stdio.h>
#include<stdlib.h>
int main(){
    int target,result;
    while(1){
        printf("Please input your target: ");
        scanf("%d",&target);//no space
        if(feof(stdin)){
            break;
        }
        printf("test\n");       
    }
}

成功了

enter image description here

C 输入 扫描 eof feof

评论

1赞 Barmar 1/5/2021
你之前不需要空格,因为它总是跳过空格来读取一个数字。%d
0赞 Test Raw 1/5/2021
但是 scanf(“%s”,a);将 \n 保存在缓存中
0赞 Barmar 1/5/2021
没关系。正如我所说,跳过空格,就是空格。%d\n
0赞 Test Raw 1/6/2021
如果现在不是 %d 而是 %s,那么可以在 %s 之前添加空格来检测 eof?
0赞 Barmar 1/6/2021
%s还可以跳过空格来阅读一个单词。

答: 暂无答案