counting characters

Here's my code so far. When I run the program it simply just outputs "charCount0." Anyone know why it's not counting? Also, how do you get your messages to look like the compiler?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
//ifstream inputFile; // File stream Object
char ch;
int charCount = 0;

string filename;
string str;
ifstream inputFile;

cout << "========================================================" << endl;
cout << " HTML File Analyzer" << endl;
cout << "========================================================" << endl;

// ask user to enter valid filename
cout << "Enter valid filename (no blanks!): ";
cin >> filename;

inputFile.open(filename.c_str());

// if file not valid ask for new filename
while(!inputFile)
{
inputFile.clear();
cout << "Re-Enter a valid filename: ";
cin >> filename;
inputFile.open(filename.c_str());
}

cout << "========================================================" << endl;
cout << " Text of the File" << endl;
cout << "========================================================" << endl;

// reading text of file
inputFile.get (ch);

while (inputFile)
{
cout << ch;
inputFile.get (ch);
}

cout << "========================================================" << endl;
cout << " End of Text" << endl;
cout << "========================================================" << endl;

cout << "Analysis of file" << endl;
cout << "----------------" << endl;

inputFile.get (ch);

while (inputFile)
{
charCount ++;
cout << ch;
inputFile.get (ch);
}

cout << "charCount" << charCount << endl;
after printing all the text from the file, get pointer has reached end of file.
you have to reset it.
see http://www.cplusplus.com/reference/iostream/istream/seekg/
You have two while loops and it looks like the first would have read all characters without counting anything. what makes you think that the second loop would execute even one time unless you reset the file's position back to the beginning? Take a look at the istream's seekg member function and also learn to use the debugger. You could easily trouble shoot this simply be stepping through the execution within a debugger.

Better yet, eliminate the second loop and simply count the characters as you read them in the first loop. I can't determine any good reason to have two loops for this program.
Last edited on
Use code tags next time please.
Topic archived. No new replies allowed.