繁体   English   中英

C++ 从文件中读取 fstream 数据不会返回正确的值。 inputFile.tellg 返回 -1

[英]C++ Reading fstream data from a file does not return correct values. inputFile.tellg returns -1

我试图从一个输入文件中读取数据,该文件的第一行包含一个整数(表示文件中列出的图像数量),第二行包含一个浮点数(用于主程序中的其他计算)和浮点数以图像文件名结尾的每一行的值都在同一个 data.txt 文件中。 data.txt 文件的最后一行包含对数据的用途的简要说明,但程序不读取该数据。 当我尝试读取数据并将其打印到屏幕上时,这些值不正确。 data.txt 文件的第一行是 5,但是当我打印出来时,我得到了一个 0,这是我将它初始化的。 我相信第二行是一个浮点值,它也输出为 0,这也是它被初始化的。 其余数据由 while 循环读入,仅打印出部分数据但不打印任何数据。 我插入了一个 cout << inputFile.tellg << endl; 语句以查看文件指针指向的位置,但它返回 -1。 我完全坚持这一点。 任何见解将不胜感激。 感谢您的时间和专业知识。

请在附件中找到 data.txt 文件和 main.cpp 文件的样本副本。

数据.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 

主程序

#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:~/Desktop/test$ ./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是有意义的。 对于简单类型,如上所述,最好是显式的。

如果您需要为R使用float ,请使用

float R = 0;

暂无
暂无

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

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