简体   繁体   English

fscanf()读取数据不符合预期

[英]fscanf() reading in data not what expected

I got my fscanf() code which is reading data from a file but not what I was expecting. 我得到了fscanf()代码,该代码正在从文件中读取数据,但不是我所期望的。 It should be: 它应该是:

A 1 3
B 2 5

and so on in terminal 等等在终端

My data file has these on it 我的数据文件上有这些

A 4 7 
B 8 6 
C 4 6 
D 7 3 
E 10 2 
F 3 8 
G 1 10 

When reading out on terminal I get this... 在终端上阅读时,我得到了...

A 4 7 

 4 7 
  8 6 

 8 6 
  4 6 

 4 6 
  7 3 

 7 3 
  10 2 

 10 2 
  3 8 

 3 8 
  1 10 

 1 10 

I want the data being read on terminal to be the exact format to how it is in my text file. 我希望在终端上读取的数据与文本文件中的数据格式完全相同。 Code below is what I us 下面的代码就是我

fp = fopen("data.txt", "r");
  if (fp == NULL)
  {
    printf("File, data.txt wasn't read succesfully. \n");
    fclose (fp);
  }
  else
  {
    printf("Reading data from data.txt \n");
    //read in data
    while (1)
    {
      dataTest = fscanf(fp, "%c %d %d", &c, &t1, &t2);
      fscanf(fp,"%c", &nl);
      if (dataTest == -1) break;
      printf("%c %d %d \n", c, t1, t2);
    }

    printf("Data read succesfully ! \n");
    fclose (fp);
  }

Change this: 更改此:

  dataTest = fscanf(fp, "%c %d %d", &c, &t1, &t2);
  fscanf(fp,"%c", &nl);

To this: 对此:

  dataTest = fscanf(fp, "%c %d %d\n", &c, &t1, &t2);

Or (depending on your file-format) this: 或者(取决于您的文件格式):

  dataTest = fscanf(fp, "%c %d %d\r\n", &c, &t1, &t2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM