read data from file till end of line in C/C++

自古美人都是妖i 提交于 2019-12-04 05:48:30

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

You can see the code running at ideone.

The \n should be the escape for new line, try this instead

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);
}  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!