我只是在学习文本文件输入/输出。我输出了一个文件,其中包含一个标题和下面的 10 行数据。 我现在想把它读回主函数。如果我在文本文件中省略标题,这对我有用,但如果我保留标题,我会得到一个无限循环。 如何在读回此数据时跳过第一行(标题行),或者如果可能的话,读回标题和数据? 这是我目前所拥有的:
void fileRead(int x2[], double y2[], int& n, char filename)
{
ifstream fin ("pendulum.txt"); // fin is an input file stream
if(!fin) //same as fin.fail()
{
cerr << "Failure to open pendulum.txt for input" << endl;
exit(1);
}
int j = 0, dummy = 0; //index of the first value j and dummy value
while(!fin.eof()) //loop while not end of file
{
fin >> dummy >> x2[j] >> y2[j];
cout << setw(5) << fixed << j
<< setw(12) << scientific << x2[j] << " "
<< setw(12) << y2[j] << endl; //print a copy on screen
j += 1;
}
fin.close(); //close the input file
}
最佳答案
您可以先读取文件头,然后读取您想要的真实内容如下:
string line;
getline(fin, line);//just skip the line contents if you do not want header
while (fin >> dummy >> x2[j] >> y2[j] )
{ //^^if you do not always have a dummy at the beginning of line
//you can remove dummy when you read the rest of the file
//do something
}
关于c++ - 如何跳过文本文件中的标题行并将其余数据读回主函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16068997/