从文件中读取数据,直到在C / C行结束++ [英] read data from file till end of line in C/C++

查看:217
本文介绍了从文件中读取数据,直到在C / C行结束++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是常见的读取,直到文件结束,但我很感兴趣,我怎么能读取文本文件数据(一串数字),直到的的的结束?我得到了任务读几大系列,从一个文件编号,这是定位在新的线路。这里被输入的一个示例:

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

第一系列:1 2 53 7 27 8

First series: 1 2 53 7 27 8

第二个:67 5 2

Second one: 67 5 2

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

Third one: 1 56 9 100 2 3 13 101 78

我必须从文件分别读取它们,但每一个直到行末。我有这个code:

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?

推荐答案

使用与fgets ()读一个完整的线,然后用解析线(可能与strtol())。

Use fgets() to read a full line, then parse the line (possibly with 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。在ideone 运行。

这篇关于从文件中读取数据,直到在C / C行结束++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆