Originally Posted by
182
Just thought of something else how would you do it if you wanted to search for two words such as "hi my name is kim" and you want to find hi and kim but you do not know how many words will be seperating them in the text file?
A stringstream might be a easy way to do this. It makes it easier because it will automatically skip whitespace. Here's an example which may give you some ideas.
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string filename = "file.txt";
ifstream in(filename.c_str());
if (!in.is_open())
{
cout << "Unable to open file." << endl;
cin.get();
return 1;
}
string line;
bool found_hi = false;
while (getline(in, line))
//while (getline(cin, line))
{
istringstream iss(line);
string word;
while (iss >> word)
{
cout << word << endl;
if (found_hi == true)
{
if (word == "kim")
{
cout << "Found hi and kim." << endl;
}
}
else if (word == "hi")
{
found_hi = true;
}
}
}
}