How do I read the number of characters and lines in a file properly?

First of all, I MUST pass by reference. My instructor said that the line counting & character counting SHOULD be done in the same function (but if I'm desperate I can separate them into 2). The counting lines portion is correct, however I'm not sure how to properly write the code to count the characters. My instructor told me that I need to use ch = inFile.get() but this code I have here isn't working.

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

// Function Prototypes
void readFilename(ifstream&, string&);
void countCharsLines(ifstream&, int&, int&, char&);

int main()
{
// Variables
ifstream inFile;
string filename;
int countLines;
int countChars;
char ch;
int index;
string array[index];

// Function Calls
readFilename(inFile, filename);
countCharsLines(inFile, countLines, countChars, ch);

cout >> countLines >> countChars >> ch;
return 0;
}

// Function: countCharsLines
void countCharsLines(ifstream &inFile, int &countLines, int &\
countChars, char &ch)
{
// Variables
string line;
countLines = 0;
countChars = 0;

while(!inFile.eof())
{
getline(inFile,line);
countLines++;
while(!inFile.eof())
{
ch = inFile.get();
countChars++;
}
inFile.close();
}
inFile.close();
}
You are closing your inFile in the while loop. That's a problem! Second, inFile.get() isn't exactley useful at this moment because we have a string that already has this information calculated. Use the .size() function!

Finally, I'm not sure why you pass &ch into the function. As far as I can see, you use it as a space filler so that you can use inFile.get() (which isn't really required). I don't know what you are planning to return with this, but currently it only returns the last character in the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Function: countCharsLines
void countCharsLines(ifstream &inFile, int &countLines, int &countChars)
{
	// Variables
	string line;
	countLines = 0;
	countChars = 0;

	while(!inFile.eof())
	{
		getline(inFile,line);
		countLines++;
		
		countChars += line.size(); // Counts the characters.
	}
	inFile.close();
}
Topic archived. No new replies allowed.