【问题标题】:getline reads same line (C++,istream)getline 读取同一行(C++,istream)
【发布时间】:2023-03-24 07:00:01
【问题描述】:

我尝试在两个文本文件之间找到相同的行。

while (getline (texta,str1)){
        while (getline (textb,str2)){
        cout<<str1<<str2<<endl;
    }}

第一个虽然工作得很好,但第二个只是阅读第一部分文本然后退出。我尝试了不同的文本,但没有用。

如果你想查看所有代码:

void similars(string text1,string text2){
    string str1,str2;
    ifstream texta(text1.c_str());          
    ifstream textb(text2.c_str());

    if(texta.is_open() && textb.is_open()){
        while (getline (texta,str1)){
            while (getline (textb,str2){
                cout<<str1<<str2<<endl;
            }
        }
    }
    else cout << "Unable to open file"; 

}

【问题讨论】:

  • 请发布您的示例输入、生成的输出以及生成的输出有什么问题。
  • 您在第二个 while 循环中缺少 ) 顺便说一句
  • 是的,我刚看到 :D 谢谢
  • 你从texta读了一行,然后读到textb到筋疲力尽。由于后者到达文件结尾,因此所有读取它的尝试都会进一步失败。在你看来,str2 在第一次通过外循环之后就再也不会改变它的值了。

标签: c++ iostream


【解决方案1】:

不要把不该做的事情混在一起 考虑这个例子:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


void similars(string text1, string text2)
{
    string str1, str2;
    ifstream texta(text1.c_str(), ios::in);          
    ifstream textb(text2.c_str(), ios::in);

    cout << "text1: " << endl << endl;
    while(!texta.eof())
    {
        getline (texta, str1);
        cout << str1 << endl;
    }

    cout << endl << endl;

    texta.close(); // closing safely the file

    cout << "text2: " << endl << endl;
    while(!textb.eof())
    {
        getline (textb, str2, '\n');
        cout << str2 << endl;
    } 

    textb.close();

    cout << endl;

}

int main()
{
    system("color 1f");

    string sText1 = "data1.txt";
    string sText2 = "data2.txt";
    similars(sText1, sText2);

    system("pause");
    return 0;
}

只需使用记事本或任何文本编辑器创建两个文本文件,将它们重命名为“text1.txt”、“text2.txt”并在其中放入一些文本并保存并关闭。然后运行程序。

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 2021-12-05
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 2018-07-02
    • 2015-06-13
    相关资源
    最近更新 更多