1

我一直在研究一个 C++ 程序,我在其中读取文件内容然后复制到另一个文件,但它似乎总是跳过第一行。我见过其他人对此有问题,他们使用了这些代码行:

file.clear();
file.seekg(0);

重置位置,但它对我不起作用。我已经在多个地方尝试过,但仍然没有运气。有任何想法吗?这是我的代码。

ofstream write("Mar 23 2013.txt");

for(int x = 1; x <= 50; x++){

    stringstream ss;
    ss << "MAR23_" << x;

    ifstream file(ss.str().c_str());

    if(!file.is_open())
        cout << ss.str() << " could not be opened/found." << endl;
    else{  

        while(getline(file,line)){

            file >> time >> ch >> sensor1 >> ch >> temp >> ch >> 
                    sensor2 >> ch >> sensor3;

            file.ignore(numeric_limits<streamsize>::max(), '\n');

            //output = convertEpoch(time);

            write << time << "  Temperature:" << temp << "ºF  S1:" <<
                        sensor1 << "  S2:" << sensor2 << "  S3:" << 
                        sensor3 << endl;

        }
        file.close();
    }  
}

write.close();

return 0;
4

2 回答 2

9

您错过了第一行,因为您将其读入line. 事实上,你应该错过的不仅仅是第一行。

从文件中读取后,请使用字符串流。

while (std::getline(infile, line))
{
    std::istringstream iss(line);
    iss>> time >> ch >> sensor1 >> ch >> temp >> ch >> 
                    sensor2 >> ch >> sensor3;
// ...


}
于 2013-04-04T00:46:03.700 回答
2

您可以通过两种方式读取文本文件。逐行、使用getline或逐项使用>>getline将一行文本读入其参数;getline在您的代码中调用 to 之后,line有已读入​​的文本。完成此操作后,提取器file >> time >> ch ...从停止的位置读取getline

于 2013-04-04T00:51:02.047 回答