0

我正在尝试读取此 .csv 文件,这是数据示例:

1.33286E+12 0   -20.790001  -4.49   -0.762739   -3.364226   -8.962189

1.33286E+12 0   -21.059999  -4.46   -0.721878   -3.255263   -8.989429

问题出在第一列第 1 行和第 2 行。在 excel 文件中,它说单元格中的数字显示为 1.33286E+12,当您单击单元格时,它说它们是 1332856031313 和 1332856031328,但程序正在读取它们如 1.33286E+12 但我需要整数 1332856031313 和 1332856031328。

编码:

inputfile.open(word1.c_str());
while (getline (inputfile, line)) //while line reads good
{
  istringstream linestream(line); //allows manipulation of string
  string str;

while (getline (linestream, item, ',')) //extract character and store in item until ','
    {

  char * cstr, *p; 
  cstr = new char [item.size()+1]; 
  strcpy(cstr, item.c_str()); 
  p = strtok(cstr, " "); 

  while (p!=NULL) //while not at the end loop
    {      // double e = atof(p); // coverts p to double
        value++;
        if( value == 1)
                {     double e = atof(p); // coverts p to double
          if(m ==1)
          cout << time[0]<<"\n";

          ostringstream str1;
           str1 << e;
          str = str1.str();
          string str2;
          str2.append(str.begin(), str.end());
          const char * convert = str2.c_str();
          e = atof(convert);
         time[m] = e*0.001;
          m++;
          //if(m >=192542)
          //cout << time[m-1]<<"\n";

        }

               p = strtok(NULL, " ");
    }
  delete[] cstr; //delete cstr to free up space.
}
count ++;
value = 0;
}
inputfile.close();
4

2 回答 2

2

如果数字 1332856031313 被序列化为 1.33286E+12,则无法在反序列化过程中将其取回。这 6 个额外有效数字形式的信息永远消失了。您需要确保生成 CSV 文件时以全精度保存。我不知道您如何使用 Excel 做到这一点。

此外,您对atofand的使用const char*不是很 C++ 风格。考虑使用类似的代码

double a, b, c, d;
linestream >> a >> b >> c >> d;

反而。

于 2012-06-15T14:43:31.797 回答
0

Rook 打败了我,但我会提出一个建议。使用循环进行解码,测试字符串流状态。好的,有两个建议:将您的代码分解为函数。将所有内容放在一个大块中会更难理解。

    void DecodeLine(const std::string &sLine, 
                    std::vector<double> &vResults)
    {
        std::istringstream istr(sLine);
        double d = 0;
        istr >> d;
        while (!istr.fail())
        {
            vResults.push_back(d);
            istr >> d;
        }
    }
于 2012-06-15T15:43:20.007 回答