【问题标题】:C++ - while(getline) doesn't get the first line of fileC++ - while(getline) 没有得到文件的第一行
【发布时间】:2013-03-25 21:46:43
【问题描述】:

我一直在开发一个 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;

【问题讨论】:

  • 尝试打印出包含的行。您将看到文件的第一行。你不能读两遍。 :)
  • 我假设您在此代码块之外的某处声明了一堆变量...
  • 您用getline 阅读了第一行,然后从不使用它。到那时,溪流已经过去了。
  • 开始习惯将 for 循环写成更惯用的 for(int i = 0; i
  • @Tomas 是的,这只是代码的一部分

标签: c++ reset ifstream getline


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 如果您也解释一下为什么 =),这个答案会更好
    • @stardust_ 哇!反应迅速。谢谢你,效果很好。
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 2011-11-29
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    相关资源
    最近更新 更多