Need help with reading in files.
Well, Ive been struggling trying to get a few of these concepts to work using the getline command and others.
I want to allow a user to enter any search string, including blanks.
**Ive done this**
I want create a final result showing what string was searched for showing each line of text where the search
string occurs.
**Im struggling on how I can display the entire line that the word is found on.**
Also the line number in the file where it occurs and what position in the line the string is located.
** Struggling with doing this , Not sure of how to implement the .find , . size , and .substr **
When the last string is read, I want to report the total
number of occurrences of the string that were found and
how many total lines were in the file.
**Ive done this too**
Here is my code thus far.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream Istream;
ofstream Ostream;
int counter = 0;
int line = 1;
int totalLines = 0;
string stringLine;
string userDefinedSearch;
Istream.open("shakespeare.txt");
if (Istream.fail() )
{
cout << "Error opening input file!";
cin.get();
return 1;
}
Ostream.open("s_word.txt");
if (Ostream.fail() )
{
cout << "Error creating output file!";
cin.get();
return 1;
}
cout << "Please enter the word you are looking for : " ;
getline(cin,userDefinedSearch);
while (Istream != 0)
{
Istream >> stringLine;
totalLines++;
if (stringLine == userDefinedSearch)
{
counter++;
cout << userDefinedSearch << endl;
Ostream << userDefinedSearch << endl;
Ostream << counter << ") occurence is on line: " << line << " " << userDefinedSearch << endl;
cout << counter << ") occurence is on line: " << line << " " << userDefinedSearch << endl << endl;
}
else
{
}
}
Ostream << counter << " occurences of the word: " << userDefinedSearch << endl << endl;
cout << counter << " occurences of the word : " << userDefinedSearch << endl << endl;
cout << "There is " << totalLines << " lines in this file." << endl;
Ostream << "There is " << totalLines << " lines in this file." << endl;
Istream.close();
Ostream.close();
return 0;
}
Here is a portion of the output.
Code:
Please enter the word you are looking for : love
.
.
.
.
.
.
.
.
.
.
.
love
1283) occurence is on line: 1 love
love
1284) occurence is on line: 1 love
1284 occurences of the word : love
There is 939197 lines in this file.
I just want the entire line that the word is found on displayed as well as its position in the file. Just kind of confused on how to display the entire actual line the searched word is found in. As well as the format of using the commands to find its position.
Any help would be wonderful. Thanks.