If you know there are two words and what they are, all you need is this:
ifstream file("file.txt"); string str; while (file >> str){ if (str.find("Computer") != string::npos){ file >> str; if (str.find("screen") != string::npos) { //// } } }
But more likely, you are asking to find a single string that might be two words, or three or more.
Then, can you count on the string being on a single line? In which case, @Ashalynd's solution will work. But if the string might be broken it will fail. You then need to handle that case.
If your file is "small" - i.e. can easily fit in memory, read in the whole thing, remove line breaks and search for the string.
If it is too large, read in lines as pairs.
Something like this:
std::ifstream file("file.txt"); std::string str[2]; int i = 0; std::getline (file,str[i]); ++i; while (std::getline (file,str[i])) { int next_i = (i+1)%2; std::string pair = str[next_i] + " " + str[i]; if (pair.find("Computer screen") != std::string::npos) { //// } i = next_i; }
All this assumes that the possible white space between the words in the string is a single space or a newline. If there is a line break with more white-space of some kind (e.g. tabs, you need either to replace white-space in the search string with a regex for white-space, or implement a more complex state machine.
Also, consider whether you need to manage case, probably by converting all strings to lower case before the match.
str.find("Computer screen")?file >> stris used,str.find("Computer screen")won't work.is_open()andgetline(for example). Note that matching multiple words in a string works just fine in theory.