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.
#include <iostream>
#include <string>
#include <fstream>
usingnamespace 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?
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: