I'm creating a program that will open a file and search for a desired word within the text. I created the following word bank...
Lawyer
Smith Janes
Doctor
Michael Zane
Teacher
Maria Omaha
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
// Declarations
string reply;
string inputFileName;
ifstream inputFile;
char character;
cout << "Input file name: ";
getline(cin, inputFileName);
// Open the input file.
inputFile.open(inputFileName.c_str());
// Check the file opened successfully.
if ( ! inputFile.is_open())
{
cout << "Unable to open input file." << endl;
cout << "Press enter to continue...";
getline(cin, reply);
return 1;
}
Now that I save the whole file into a string how could I search inside that string for a specific word I'm looking for...
I'm learning C++ from this Website http://www.cprogramming.com/tutorial/lesson10.html
I think you use string::find
but I couldn't find much reference on how to search beside this wesite..
http://www.cplusplus.com/reference/string/string/find/
This section will display the whole file.
string original;
getline(inputFile, original, '\0');
cout << original << endl;
cout << "\nEnd of file reached\n" << endl;
// Close the input file stream
inputFile.close();
cout << "Press enter to continue...";
return 0;
}
This is how I think the program should act...
Please enter a word: Smith Janes
Smith Janes Lawyer
another example....
Please enter a word: Doctor
Michael Zane Doctor
find
returns the position (zero based offset) in the string where the word is found. If the word is not found it returnsnpos
.