读取到文件末尾是很常见的,但是我对如何从文本文件读取数据(一系列数字)直到行尾很感兴趣?我得到了从文件中读取几组数字的任务,这些数字以新行放置。这是输入示例:

1 2 53 7 27 8
67 5 2
1 56 9 100 2 3 13 101 78

第一个系列:1 2 53 7 27 8

第二个:67 5 2

第三名:1 56 9 100 2 3 13 101 78

我必须从文件中分别读取它们,但是每一个都读取到行尾。我有以下代码:
    #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);
     }

它一直读取到文件末尾,因此它并没有达到我的期望。你有什么建议?

最佳答案

使用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;
}

您可以看到code running at ideone

关于c - 在C/C++中从文件读取数据直到行尾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14001907/

10-11 23:03
查看更多