C语言 在 C/C++ 中从文件读取数据直到行尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14001907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
read data from file till end of line in C/C++
提问by Eszter
It is common to read until end of file, but I am interested in how could I read data (a series of numbers) from a text file until the end of a line? I got the task to read several series of numbers from a file, which are positioned in new lines. Here is an example of input:
这是常见的阅读到文件结束,但我很感兴趣,我怎么能读取文本文件数据(一串数字),直到结束行?我的任务是从文件中读取几个系列的数字,这些数字位于新行中。下面是一个输入示例:
1 2 53 7 27 8
67 5 2
1 56 9 100 2 3 13 101 78
First series: 1 2 53 7 27 8
第一个系列:1 2 53 7 27 8
Second one: 67 5 2
第二个:67 5 2
Third one: 1 56 9 100 2 3 13 101 78
第三个:1 56 9 100 2 3 13 101 78
I have to read them separately from file, but each one till the end of line. I have this code:
我必须从文件中单独阅读它们,但每一个都要读到行尾。我有这个代码:
#include <stdio.h>
FILE *fp;
const char EOL = '\0';
void main()
{
fp = fopen("26.txt", "r");
char buffer[128];
int a[100];
int i = 0;
freopen("26.txt","r",stdin);
while(scanf("%d",&a[i])==1 && buffer[i] != EOL)
i++;
int n = i;
fclose(stdin);
}
It reads until the end of the file, so it doesn't do quite what I would expect. What do you suggest?
它一直读到文件末尾,所以它并没有像我期望的那样做。你有什么建议?
采纳答案by pmg
Use fgets()to read a full line, then parse the line (possibly with strtol()).
使用fgets()读取整行,然后解析该行(可能使用strtol())。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char buffer[10000];
char *pbuff;
int value;
while (1) {
if (!fgets(buffer, sizeof buffer, stdin)) break;
printf("Line contains");
pbuff = buffer;
while (1) {
if (*pbuff == '\n') break;
value = strtol(pbuff, &pbuff, 10);
printf(" %d", value);
}
printf("\n");
}
return 0;
}
You can seethe code running at ideone.
您可以看到在 ideone 上运行的代码。
回答by rbtLong
The \n should be the escape for new line, try this instead
\n 应该是换行符的转义符,试试这个
const char EOL = '\n';
did u get it working? this should help:
你让它工作了吗?这应该有帮助:
#include <stdio.h>
FILE *fp;
const char EOL = '\n'; // unused . . .
void main()
{
fp = fopen("26.txt", "r");
char buffer[128];
int a[100];
int i = 0;
freopen("26.txt","r",stdin);
while(scanf("%i",&a[i])==1 && buffer[i] != EOF)
++i;
//print values parsed to int array.
for(int j=0; j<i; ++j)
printf("[%i]: %i\n",j,a[j]);
fclose(stdin);
}

