Another word count problem
Nov 30, 2013 at 9:05pm UTC
I have to write a program that counts the words in a *.txt file. So far I've been able to figure out how to get a character count. I would like to be able to do a character, letter (ie: not count spaces or punctuation) and word count.
Here's what I have so far (it compiles and runs fine):
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 32 33 34 35 36 37 38 39 40
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <iomanip>
int main()
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
char inputFile[256];
cout << "Enter a file name: \n" ;
cin >> inputFile;
cout << "The file name entered is: " << inputFile << endl;
in_stream.open(inputFile);
if (in_stream.fail())
{
cout << "Input file failed to open\n" ;
system("pause" );
exit(1);
}
int count(0), words(0);
char letter, current;
while (!in_stream.eof())
{
in_stream.get(letter);
count++;
}
cout << "There are " << count << " characters in the file " << inputFile << "." << endl;
in_stream.close();
system("pause" );
return 0;
}
Nov 30, 2013 at 11:30pm UTC
Got it working.
I used the isspace() function to count the spaces and then add one:
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 32 33 34 35 36 37 38 39 40 41 42 43
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <iomanip>
int main()
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
char inputFile[256];
cout << "Enter a file name: \n" ;
cin >> inputFile;
cout << "The file name entered is: " << inputFile << endl;
in_stream.open(inputFile);
if (in_stream.fail())
{
cout << "Input file failed to open\n" ;
system("pause" );
exit(1);
}
int count(0), words(0);
char space = ' ' ;
char letter;
while (!in_stream.eof())
{
in_stream.get(letter);
if (isspace(letter))
{
count++;
}
}
cout << "There are " << count + 1 << " words in the file " << inputFile << "." << endl;
in_stream.close();
system("pause" );
return 0;
}
Topic archived. No new replies allowed.