getline读取同一行(c++,istream)

getline reads same line (C++,istream)

本文关键字:一行 c++ istream 读取 getline      更新时间:2023-10-16

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

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"; 
}

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

#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",并在其中放入一些文本,保存并关闭。然后运行程序