There are four big issues.
1. eof() does not mean what you think it means.
2. The comma operator in line 20 does not mean what you think it means.
3. the str2 on line 27 which you read into is NOT the str2 you construct a stringstream with on line 29. Look at line 28 and tell me what it's doing there.
4. You have return in both the if and else at lines 37 and 40. Regardless of anything else, all of this is happening exactly once.
It looks like you need to swap lines 27 and 28. Compare your line order for "str2" to that of "str1". Yeah, we've all made this mistake--one that tired eyes often don't spot.
let me just say i want to build up on the code below,instead of just using a single given string. it reads from a whole file "source" for all the matchs there is and then writes them to a output file.........
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
usingnamespace std;
struct person {
string firstname;
string surname;
string gender;
int id;
};
int main()
{
ifstream input;
ifstream source;
//ofstream output;
//ofstream notfound;
input.open("input.txt");
source.open("source.txt");
//output.open("output file.txt");
//notfound.open("Not Found.txt");
// foreach line of input....
string input_line;
while( getline(input,input_line) ) {
stringstream i_line(input_line);
person input_person;
i_line >> input_person.firstname
>> input_person.surname
>> input_person.gender
>> input_person.id;
// search the source for a matching name
source.clear();
source.seekg(0);
bool found = false;
string source_line;
while ( !found && getline(source,source_line) ) {
stringstream s_line(source_line);
person source_person;
s_line >> source_person.firstname
>> source_person.surname
>> source_person.gender
>> source_person.id;
// found them!
if ( source_person.firstname == input_person.firstname ) {
found = true;
}
}
// and output...
if ( !found ) {
cout << "No match for " << input_person.firstname << endl;
} else {
cout << "Matched " << input_person.firstname << endl;
}
}
return 0;
}
$ g++ foo.cpp
$ ./a.out
Matched Lucy
Matched Mark
Matched john
Matched Lisa
Matched Chitalu
No match for Frank
Matched Malika
Matched Raymod
Matched Lucy
Matched Jack
No match for Oka
Matched Emmanucle
Matched Brian
Matched Lisa
Matched Prince