wrong results from a code

I need to count the number of character, lines and spaces in a file and the following code displays wrong results in the number of lines. Does anyone have any idea why and how can it be written in a better way?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
	ifstream input;
	input.open("textdoc.txt");
	char character;
	int numberOfCharacters = 0;
	int numberOfSpaces = 0;
	int numberOfLines = 0;
	input.get(character);
	while (!input.eof())
	{
		input.get(character);
		numberOfCharacters +=1;
		if (character == ' ') {
			numberOfSpaces += 1;
		}
		else if (character == '\n') {
			numberOfLines += 1;
		}
	}
Last edited on
What was the output and how does the input file look like.
One problem is the use of !input.eof() which doesn't work as you might expect - Google will tell you why. Normal way is while (input.get(character))

Another problem is that you read one character before the while loop - WHY ?
It's possible that the file doesn't end with '\n' so your line count is 1 short.
Your points are all valid.

That said, if you subscribe to the Unix definition of a line, then characters after the last newline in the file are not part of a line. :3 This would make TC's algorithm technically correct... Based on TC's description it isn't clear that is what is meant by "incorrect" though.
Yes, the line count is 1 short, how do you suggest I should write it so it's accurate?
Use:
while getline( input, line ) { ... }

Add a count to the number of lines for each loop.
Keep appending the length of the new line to get the number of characters.
Scan each line (range-based for loop) and add a count for each space.
Topic archived. No new replies allowed.