我试图从输入文件中读取数据,该输入文件包含第一行的整数(表示文件中列出的图像数),第二行上的浮点数(这用于主程序中的其他计算)和浮点数以相同data.txt文件中的图像文件名称结尾的每个后续行上的值。 data.txt文件的最后一行包含数据用于但未被程序读取的简要说明。当我尝试读取数据并将其打印到屏幕时,值不正确。 data.txt文件的第一行是5,但当我打印出来时,我得到一个0,这是我初始化它。第二行是我认为的浮点值,它也输出为0,这也是它初始化的值。其余的数据是通过while循环读入的,只有部分数据被打印出来但没有打印出来。我插入了一个cout << inputFile.tellg << endl;用于查看文件指针指向的位置但返回-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:〜/ Desktop / test $ ./main data.txt
开始
-1
N现在为0
R现在为0
-1
至少我会期望N为5,因为我可能有R的类型错误或者一旦读取数据可能需要更多的计算,我不确定。我只是不明白为什么文件指针显示它位于-1位置。
问题很可能是由R
的声明引起的。
auto R = 0;
上述声明使R
成为int
,而不是double
或float
。
使用
double R = 0;
你可以用
auto R = 0.0;
但我不推荐它。使用auto
是有意义的类型是长卷曲和类型繁琐。对于简单类型,如上所述,最好是明确的。
如果你需要使用float
用于R
,请使用
float R = 0;