读取一个充满数字的文件时得到零

Getting Zeros When Reading A File Full of Numbers

本文关键字:文件 数字 满数字 一个 读取      更新时间:2023-10-16

我正在尝试读取一个有几百行的文件。每一行看起来大致如下(请记住,这些不是实际数字。只是格式的一个示例。)R 111.111 222.2222 123456 11 50.111 51.111

我试着用fscanf读取这个文件,然后打印出一些值,但当我打印出这些值时,所有变量都为0。我已经检查了文件,没有一行的所有变量的值都为0。我在用C++写作。

#include <fstream> 
#include <iostream> 
#include <string>
using namespace std;
int main(int argc, char** argv)
 {
  FILE *myfile;
  myfile = fopen("tmp.txt", "r");
  string type;
  float dx;
  float dy;
  float intensity;
  int nsat;
  float rmsy;
  float rmsx;
  if (myfile == NULL) exit(1);
  else
    {
      while ( ! feof (myfile) )
       {
      fscanf(myfile,"%s %f %f %f %i %f %fn",&type, &dx, &dy, &intensity, &nsat, &rmsx, &rmsy);
      printf("F %f %f %f %i %f %fn", dx, dy, intensity, nsat, rmsx, rmsy);
       }
    }
}

您可以使用std::ifstream 执行此操作

注意:这段代码并不假设输入文件的格式总是很好,并且在一个规则中没有丢失任何值

#include <fstream> //for ifstream
#include <string> //for strings
ifstream stream ( "tmp.txt", ios::in );
string type;
float dx;
float dy;
float intensity;
int nsat;
float rmsy;
float rmsx;
while ( stream >> type){
    stream >> dx;
    stream >> dy;
    stream >> intensity;
    stream >> rmsy;
    stream >> rmsx;
    cout << type << 't'
        << dx << 't'
        << dy << 't'
        << intensity <<'t'
        << rmsy << 't'
        << rmsx << endl;
}

和input.txt=

 R 111.1111 222.2222 123456 11 50.111
 T 111.1111 222.2222 123456 11 50.111

这会再次打印出来,注意这是更惯用的C++。

输出=

R   111.111 222.222 123456  11  50.111
T   111.111 222.222 123456  11  50.111

您的代码有多个问题,但是:

问题是格式字符串开头的%s。CCD_ 3匹配完整的行,因此包含所有值。

如果您确信数字前面只有一个字符,那么也许您可以使用%c

还要注意,您传递了一个指向scanfstd::string指针。这是无效的,因为scanf需要一个char缓冲区来存储字符串(%s),这根本不是一个好主意,因为您不知道所需的缓冲区长度。

这对我有效:

#include <fstream> 
#include <iostream> 
#include <string>
using namespace std;
int main(int argc, char** argv)
{
  FILE *myfile;
  myfile = fopen("tmp.txt", "r");
  char type;
  float dx;
  float dy;
  float intensity;
  int nsat;
  float rmsy;
  float rmsx;
  // The NULL-if should be here, but left out for shortness
  while ( ! feof (myfile) )
  {
    fscanf(myfile,"%c %f %f %f %i %f %f",&type, &dx, &dy, &intensity, &nsat, &rmsx, &rmsy);
    printf("F %f %f %f %i %f %fn", dx, dy, intensity, nsat, rmsx, rmsy);
  }
}