#include "stdio.h"
int main(){
char str[20];
while(scanf("%19[^\n]",str)==1){
printf("%s",str);
}
return 0;
}
编译使用:
$ gcc file.c -o file
$ file < input.txt
程序仅读取文件 input.txt
中的第一行:
hello this is
a test that
should make it
happen
我想让程序读取完整的文件,请帮忙
最佳答案
添加一个空格:
while(scanf(" %19[^\n]",str)==1){
^
该空格(不直观地)占用任何空白,包括\n
,否则您将不会处理它。
当然,通常使用例如fgets()
和 sscanf()
而不是 scanf()
来解析输入。
这会稍微改变您的代码逻辑,但也许可以更好地捕捉您的意图。任何仅跳过 \n
而不是所有空白的尝试,如下所示:
while(scanf("%19[^\n]\n",str)==1){
将会失败,因为这里第二个\n
与空格完全相同。
关于c - 使用c程序从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22483633/