[英]How to check EOF when reading txt file using ifstream
I want to read a text file in c++ using ifstream
to know the number of words, characters, lines. 我想使用ifstream
读取c ++中的文本文件,以了解单词,字符,行数。
unsigned int wordNum = 0;
unsigned int lineNum = 0;
unsigned int charNum = 0;
char check;
ifstream in("example_2_4.txt");
char temp[30];
if (!in.is_open()) {
cout << "File opening error!" << endl;
}
while (!in.eof()){
in.getline(temp, 30);
wordNum += countWord(temp);
charNum += countChar(temp);
lineNum++;
in.clear();
}
The problem is that eof()
does not work since there exists a line that exceeds 30 characters. 问题是eof()
不起作用,因为存在一行超过30个字符的行。
I've changed !in.eof()
to in>>check
and it works well but it reads a character so I can't count all characters in line. 我已经将!in.eof()
更改为in>>check
,并且效果很好,但是它读取了一个字符,因此我无法对所有字符进行计数。
I shouldn't use string
class and can't change buffer size. 我不应该使用string
类,也不能更改缓冲区大小。
Is there any proper way to check eof
? 有什么适当的方法检查eof
吗?
I'm not entirely sure what you are asking, but ifstream::getline() sets the failbit when it tries to read a string that's too long. 我不确定您要问什么,但是当ifstream :: getline()尝试读取太长的字符串时,它会设置故障位 。 In your case, the eof bit will never be set (even though you are clearing all the bits anyway). 在您的情况下,永远不会设置eof位(即使您仍然清除所有位)。
You can simply do: 您可以简单地执行以下操作:
while (in)
and in addition to not clearing any of the flags. 而且除了不清除任何标志。
If you want to be able to read a line that is longer than the buffer you can store it in, you need to read the file some other way, perhaps using ifstream::get() instead. 如果您希望读取的行比可以存储缓冲区的行长 ,则需要以其他方式读取文件,也许使用ifstream :: get()代替。
in.getline(temp, 30);
returns istream&
so moving it in the while loop to here while(in.getline(temp, 30))
will return false when it reaches the end of file or a read error. 返回istream&
因此将其在while循环中移动到此处while(in.getline(temp, 30))
到达文件末尾或读取错误时将返回false。
Try this: 尝试这个:
string line;
ifstream myfile ("example_2_4.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
wordNum += countWord(line);
charNum += countChar(line);
lineNum++;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
Given your constraints, I would suggest: 鉴于您的限制,我建议:
int c;
while ( (c = in.get()) != EOF )
{
++charNum;
if (isspace(c) )
{
++wordNum;
}
if ( c == '\n' )
{
++lineNum;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.