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);
                cout << "File could not be opened.\n";
                return 0;

                file.getline(fileword, 11, ' ');
                filestring.copy(fileword, 0, 11);
                if(filestring.compare(string) == 0)
                        file.getline(fileline, 51, '\n');
                        cout << fileline << endl;
        cout << "The string was found " << count << " times.\n";
        return 0;

line 12: you are attempting to use string as both c++ object type and a variable name. You have to rename it to something else

line 13: why are you using character arrays here? You can just use std::string class

string fileword, fileline;

The loop that starts on line 25 is coded wrong because eof() doesn't work the way you think. Most new programmers make this mistake and I'm not sure if its due to inexperience of terrible instructors.

The solution to this problem involved stringstream class, which will split up an entire line into individual words. This code is not 100% correct but gives you an idea of what to do.

#include <sstream>

string word, line;
while( getline(file, line) )
     stringstream str(line);
     while( str >> word)
           if( word == WordToFind)
                cout << line << "\n";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.