-1

I try to find same lines between two text files.

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

First while working very well but second one just read first part line of text and then quit. I've tried different textes but doesnt work.

If you want to look all code:

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

}
  • Please post your sample input, the generated output, and what is wrong with the generated output. – J Earls Sep 05 '16 at 22:27
  • you're missing a `)` for your second while loop BTW – kmdreko Sep 05 '16 at 22:28
  • Yeah,I just saw :D thanks – İlker Polat Sep 05 '16 at 22:29
  • 1
    Possible duplicate of [cin and getline skipping input](http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input) – Barmar Sep 05 '16 at 22:57
  • 1
    You read one line from `texta`, then read `textb` to exhaustion. Since end-of-file is reached on the latter, all attempts to read from it further fail. To you, it looks like `str2` never changes its value after that first time through the outer loop. – Igor Tandetnik Sep 06 '16 at 01:57
  • maybe the size of the second file is shorter than the first or the contrary? – Raindrop7 Sep 09 '16 at 00:27

1 Answers1

0

don't mix things those shouldn't do consider this example:

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

just create two text files with notepad or any text editor, rename them to "text1.txt", "text2.txt" and put some text in them and save and close. then run the program.

Raindrop7
  • 3,889
  • 3
  • 16
  • 27