Click here to Skip to main content
15,441,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written a code o count number of letters present in a text file and print that letters.
But it always prints an extra letter . Suppose in my File Welcome is there then it is printing Welcomee like this, kindly help.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{//ifstream is a datatype which represents the input file stream which is used to read the data from the file
    ifstream file;
    //Open File with file name countletters.txt"countletters.txt");
//n is an counter integer variable used to count the number of letters
//letter is an character variable
	int n=-1;
	char letter;
	int i;	
	//eof() is a function which represents when no file present to read the data from the file
		        cout << letter;
//Display the number of letters present in the file	
cout << "the number of letters is :" << n << endl;
//file is closed
return 0;

The EOF flag is not set when the last character has been read but when trying to read the next not available character. So you must check for EOF after reading a character and before printing it out.

Reading the character and checking for EOF can be done inside the while condition:
while (!file.get(letter).eof())
// ...
Share this answer
Member 10578683 14-Jan-15 5:45am     CRLF
It is showing error as 28 C:\Users\swetad\Desktop\Output\main.cpp:19 no match for 'operator!=' in 'file.std::basic_ifstream<char>::<anonymous>.std::basic_istream<_CharT, _Traits>::get [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::char_type = char]((* & letter)) != -0x000000001'
Jochen Arndt 14-Jan-15 6:06am     CRLF
Oops. The get(&char) version does not return the state but the stream. The get(void) version returns the character or EOF. I have updated the solution with a working statement.
1. You need to initialize "n" to zero, not -1.
2. Use "letter = file.get();" instead of "file.get(letter);".
3. Your test for "i>64&&i<91" includes 'A' through 'Z' so why not write it that way?
eg. "i >= 'A' && i <= 'Z' ... ditto for "i>96&&i<123".
4. I noticed the code prints a blank line for every character read. Not sure if that was your intent.

You will see the correct count AND no extra character at the end.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900