C 从文件中读取FSTREAM数据不会返回正确的值.inputfile.tellg返回-1



我正在尝试从一行包含整数的输入文件中读取数据(表示文件中列出的映像数),在第二行上浮动(这是用于主程序中的其他计算)和在随后的每条线上以映像文件的名称结尾的每个后续行中的浮点数。data.txt文件的最后一行包含一个简要说明数据的用途,但没有由程序读取。当我尝试读取数据并将其打印到屏幕上时,值不正确。data.txt文件的第一行是一个5,但是当我打印出来时,我会得到一个0,这是我初始化的。我相信第二行是浮点值,也是输出为0,它也是初始化的。其余的数据将以一定的循环读取,其中只有一部分被打印出来,但没有打印。我插入了一个cout<<inputfile.tellg<<端语句以查看文件指针指向的位置,但返回-1。我完全陷入了困境。任何洞察力都将不胜感激。感谢您的时间和专业知识。

请找到附加的data.txt文件的示例副本以及main.cpp文件。

data.txt

5
5.50e+11
 4.4960e+11  0.0000e+00  0.0000e+00  4.9800e+04  5.9740e+24       cat.gif
 3.2790e+11  0.0000e+00  0.0000e+00  3.4100e+04  6.4190e+23       dog.gif
 2.7900e+10  0.0000e+00  0.0000e+00  7.7900e+04  3.3020e+23     mouse.gif
 0.0000e+00  0.0000e+00  0.0000e+00  6.0000e+00  1.9890e+30  squirrel.gif
 5.0820e+11  0.0000e+00  0.0000e+00  7.5000e+04  4.8690e+24       fox.gif
This file contains an example of data stored in a text file 

main.cpp

#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
int main( int argc, char* argv[ ] )
{
      float xPosition, yPosition;
      float xVelocity, yVelocity;
      float animalMass;
      string imgFilename;
      string line;
      istringstream inputStream( line );
      auto N = 0;   // Number of items
      auto R = 0; // Real number from file
  cout << "begin" << endl;
  if( argc > 1 )
  {
    string fileName = argv[ 1 ];
    ifstream inputFile( fileName );
    inputFile.open( fileName, ios::in );
    if( !inputFile.is_open( ))
    {
      cout << setw( 5 ) << " " << "Could not open file " << fileName << "." << endl;
      cout << setw( 5 ) << " " << "Terminating program." << endl;
      exit( 1 );
    }
    else
    {
      cout << inputFile.tellg() << endl;
      inputFile >> N;
      inputFile >> R;
      cout << "N is now " << N << endl;
      cout << "R is now " << R << endl;
      cout << inputFile.tellg() << endl;
      while( inputFile >> xPosition >> yPosition
                       >> xVelocity >> yVelocity
                       >> animalMass   >> imgFilename )
      {
        cout << xPosition << " " << imgFilename << endl;
      }       
    }
  } 
}

输出如下:

OS:〜/桌面/测试$ ./main data.txt

开始

-1

n现在是0

r现在是0

-1


至少我希望n是5我不确定一旦读取数据,就需要进行R或可能需要更多的计算。我只是不明白为什么文件指针显示其位于位置-1。

问题很可能是由R的声明引起的。

auto R = 0;

上面的声明使R成为int,而不是doublefloat

使用

double R = 0;

您可以使用

auto R = 0.0;

,但我不建议这样做。当类型长时间且笨拙地输入类型时,使用auto是有道理的。对于简单的类型,如上所述,最好是明确的。

如果您需要将float用于R,请使用

float R = 0;

最新更新