在读取文件时显示额外的字符问题 [英] Displaying an extra character problem while reading a file
本文介绍了在读取文件时显示额外的字符问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个代码o计算文本文件中的字母数量并打印这些字母。
但是它总是打印一个额外的字母。假设在我的文件欢迎中,那么就是打印欢迎这样的,请帮助。
Hi,
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>
#include<conio.h>;
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
file.open("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
while(!file.eof())
{file.get(letter);
i=letter;
if(i>64&&i<91||i>96&&i<123)
{
n++;
cout << letter;
}
cout<<endl;
}
//Display the number of letters present in the file
cout << "the number of letters is :" << n << endl;
//file is closed
file.close();
getch();
return 0;
}
推荐答案
当code> EOF 标志未设置时最后一个字符已被读取,但在尝试读取下一个不可用的字符时。因此,您必须在阅读完字符后再打印出来之前检查EOF
。
阅读字符并检查EOF
可以在while条件下完成:
TheEOF
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 forEOF
after reading a character and before printing it out.
Reading the character and checking forEOF
can be done inside the while condition:
while (!file.get(letter).eof())
{
// ...
}
1。你需要将n初始化为零,而不是-1。
2.使用letter = file.get();而不是file.get(letter);。
3.你对i> 64 && i< 91的测试包括'A'到'Z'所以为什么不这样写?
例如。 i> ='A'&& i< ='Z'... ditto fori> 96 && i< 123。
4.我注意到代码为每个角色打印一个空行读。不确定这是不是你的意图。
你会看到正确的计数,最后没有额外的字符。
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.
这篇关于在读取文件时显示额外的字符问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文