text file statistics help
Jul 26, 2012 at 3:49pm UTC
If I knew why it wasn't working I wouldn't be posting on here asking for help. I've been looking at it and changing it for the last 2 hours and I still can't figure it out.
Jul 26, 2012 at 3:50pm UTC
HINT: everything inside the for() loop will print every iteration, and there is something you are passing to cout that is making it jump to a new line
Jul 26, 2012 at 4:13pm UTC
Ok, so I changed the code and it now prints out the contents but it doesn't count anything any more. I don't know how to make it go from the while loop line 32 to the for loop line 42.
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstring>
using namespace std;
int main()
{
fstream file;
int lower_count = 0;
int upper_count = 0;
int alpha_count = 0;
int space_count = 0;
int punct_count = 0;
string filename;
string line;
cout << "Enter a file name" << endl;
cin >> filename;
file.open(filename.c_str(), ios::in);
if (!file)
{
cout << "Couldn't open " << filename << endl;
return 1;
}
else
{
while (file)
{
getline (file, line);
cout << "-- File contents --" << endl;
cout << line << endl;
cout << "-- End --" << endl;
break ;
}
for (char c = file.get(); c !=EOF; c = file.get())
{
if (islower(c))
{
lower_count++;
}
if (isupper(c))
{
upper_count++;
}
if (isalpha(c))
{
alpha_count++;
}
if (ispunct(c))
{
punct_count++;
}
if (isspace(c))
{
space_count++;
}
}
}
file.close();
cout << "File statistics:" << endl;
cout << "Uppercase characters: " << upper_count << endl;
cout << "Lowercase characters: " << lower_count << endl;
cout << "Punctuation characters: " << punct_count << endl;
cout << "Alphabetic characters: " << alpha_count << endl;
cout << "Whitespace characters: " << space_count << endl;
}
Jul 26, 2012 at 5:00pm UTC
Here's the method your teacher gave you to read the file:
1 2 3 4
for (char c = file.get(); c != EOF; c = file.get())
{
//The variable "c" now contains the next character from the file
}
So something like:
1 2 3 4 5
for (char c = file.get(); c != EOF; c = file.get())
{
//The variable "c" now contains the next character from the file
cout << c;
}
Jul 26, 2012 at 5:20pm UTC
Thanks, I finally got it. When I used that it was displaying the characters on different lines. I finally got it to work. Thanks for your help.
Topic archived. No new replies allowed.