C++ 如何跳过文本文件中的标题行并将其余数据读回主函数?
我正在学习文本文件输入/输出。我已经输出了一个文件,其中包含一个头和下面的10行数据。 现在我想把它读回main函数。如果我在文本文件中省略了头,这对我来说是有效的,但是如果我将头保留在文本文件中,我会得到一个无限循环。 读回此数据时,如何跳过第一行(标题行),或者如果可能,读回标题和数据? 以下是我到目前为止的情况:C++ 如何跳过文本文件中的标题行并将其余数据读回主函数?,c++,C++,我正在学习文本文件输入/输出。我已经输出了一个文件,其中包含一个头和下面的10行数据。 现在我想把它读回main函数。如果我在文本文件中省略了头,这对我来说是有效的,但是如果我将头保留在文本文件中,我会得到一个无限循环。 读回此数据时,如何跳过第一行(标题行),或者如果可能,读回标题和数据? 以下是我到目前为止的情况: void fileRead(int x2[], double y2[], int& n, char filename) { ifstream fin ("pen
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
}
void fileRead(int x2[],双y2[],int&n,字符文件名)
{
ifstream fin(“be摆.txt”);//fin是一个输入文件流
if(!fin)//与fin.fail()相同
{
cerr假人>>x2[j]>>y2[j];
cout您可以先读取文件头,然后读取所需的实际内容,如下所示:
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
}
你最好的办法是使用
fin.ignore(10000,'\n');
这将忽略文件中的前10000个字符,或者在换行之前忽略这些字符。10000是相当任意的,应该是一个总是比最大行长的数字。伙计,那边的这位先生帮了我很多忙。你看,每个人都说要使用getline();跳过一行,但问题是有时候你不想在缓冲区中存储任何东西,所以ignore()对我来说更有意义。所以我想补充一下,支持我们同事的回答,你可以使用“numeric_limits::max()”这将使它没有限制,它将忽略,直到找到分隔符
`
#包括
#包括
#包括
使用std::streamsize;
int main(){
ifstream fin(“摆锤文件”);
fin.ignore(数值限制::max(),'\n');
}
`
#include <iostream>
#include <fstream>
#include <limits>
using std::streamsize;
int main() {
ifstream fin ("pendulum.txt");
fin.ignore(numeric_limits<streamsize>::max(),'\n');
}