I have an assignment. I have to ask the user for a string to search for in a file. The program reads each line of the file and compares each string to the user's string. It then displays the line of the file the string was found on. Lastly, I must display the number of times the string was found.
My problem is that the program runs and asks for the user to input a string, but when it tries to open the file I get an error message.
"Project Project2.exe raised exception class_STL::out_of_range with message 'Exception Object Address: 0x8F797E'. Process stopped."
Then it sends me to a line in the string.h file.
I'm lost.
Here is my code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
int count = 0;
cout << "Please enter a string for the program to search for. Maximum 10 characters.\n";
string string, filestring;
char fileword[11], fileline[51];
getline(cin, string);
cout << "The program will search the file \"file.txt\" for the string.\n";
file.open("U:\\Private\\Programming\\Assignment 11\\file.txt", ios::in);
if(!file)
{
cout << "File could not be opened.\n";
system("PAUSE");
return 0;
}
while(!file.eof())
{
file.getline(fileword, 11, ' ');
filestring.copy(fileword, 0, 11);
if(filestring.compare(string) == 0)
{
file.getline(fileline, 51, '\n');
count++;
cout << fileline << endl;
}
}
cout << "The string was found " << count << " times.\n";
system("PAUSE");
return 0;
}