Help. reading from File

Hi. So this is the question given to me.

Write a program that prompts the user for a file name, which will be the file from Problem 4. It reads the file and then tells the user the string that was originally entered and how many times it appears.

my only problem is that when I try to print out the original string it never prints out.

Here is the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(){
string phrase;
string fileName;
int times = 0;

cout << "What file are we working on? ";//prompt user for the file name
getline(cin, fileName);
fileName = fileName+".txt"; //let fileName be equal to fileName + ".txt" so							
cout << endl;				//user wont have to type in .txt

ifstream inFile(fileName);//check if the fileName exists and open it

if(inFile.is_open()){ //if the fileName exists then to this lines of code
	while(getline(inFile, phrase)){//everytime phrase gets a newline do the code inside the while loop
	times++;//add a counter to times
	}
	cout << "This is the original phrase: " << phrase << endl; //PROBLEM!
	cout << "This is how many times the phrase is repeated: " << times << endl;//prints how many times
}												//it was printed

else//if fileName does not exist show this message instead
	cout << "\nSorry, no file with that name exists in my folder\n";
inFile.close();//close the file
return 0;
}


I might have a clue to why it's not printing. is it because of the getline? probably after the while loop finishes it throws away the stored string in the phrase variable?

Thank you!
Last edited on
closed account (iGLbpfjN)
It never prints because string phrase; doesn't have a value.
Make a getline() after line 14 so that the user can enter a word to be searched.
Alos, line 19 - 21 is wrong. Every time it hits a newline it'll add +1 to times. Do something like this:
1
2
3
4
5
6
string search;

while(getline(inFile, search))
{
     if(search == phrase) times++;
}
Last edited on
Topic archived. No new replies allowed.