So I need to write a program that opens a file (which ever file the user inputs) and count the number of words example file: This &%file should!!,...
have exactly 7 words.
The if statment nested in the while loop near the bottom will give me the correct word count but only display the first character of the file, and if i comment out the if statement it doesnt count the words but it displays the file content correctly. I need it to do both. please help me. Here is my code..
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char inChar;
ifstream inFile;
int count=1;
string fileName;
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream inFile;
int count=0;
string fileName="", word="";
while (1)
{
cout << endl <<"Enter filename" << endl;
cin >> fileName;
if (fileName == "quit")
break;
inFile.open(fileName);
if (!inFile)
{
cout << "Can't open the input file.";
return 1;
}
while (inFile >> word)
{
cout << word << '\n';
count++;
}
cout << endl << "This file has " << count << " words." << endl;
inFile.close();
count = 0;
}
return 0;
}
using inFile.get(inChar) will store a char in (inChar) but you want to count the words not letters, here get function takes a char but it doesn't take a string, so you use inFile >> word this will store a string or a char think of it as cin >> word. In your code you are using both when you should use only one, and in your case you should use inFile >> word where word is a string.