#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
int main()
{
// Using this for testing.
istringstream in(
"HI bye\n""goodbye\n""\n""foo bar\n""boy girl\n""one two three\n");
string line;
while (getline(in, line))
{
istringstream iss(line);
string word1;
if (!(iss >> word1))
continue; // line had no words
string word2;
if (!(iss >> word2))
continue; // line only had one word
string word3;
if (iss >> word3)
continue; // line had more than two words
// Line had exactly two words.
cout << word1 << ", " << word2 << '\n';
}
}
Please note that if two lines begin by the same word, e.g. foo bar
foo pub
the second one will be neglected. Maybe you want to use a std::multimap instead?