如何知道下一个字符是否是C ++中的EOF [英] How to know if the next character is EOF in C++

查看:149
本文介绍了如何知道下一个字符是否是C ++中的EOF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道 ifstream 中的下一个字符是否是文件的结尾。我试图用 .peek()

I'm need to know if the next char in ifstream is the end of file. I'm trying to do this with .peek():

if (file.peek() == -1)

if (file.peek() == file.eof())

但都不行。有办法吗?

编辑:我要做的是在每个单词的末尾添加一个字母一份文件。为了这样做,我问下一个字符是否是标点符号,但这样最后一个字是没有额外的字母。我正在使用 char ,而不是 string

What I'm trying to do is to add a letter to the end of each word in a file. In order to do so I ask if the next char is a punctuation mark, but in this way the last word is left without an extra letter. I'm working just with char, not string.

推荐答案

istream :: peek() 在检测到结束时返回常量 EOF (这是不保证等于-1)文件或错误。要检查文件结尾是否稳健,请执行以下操作:

istream::peek() returns the constant EOF (which is not guaranteed to be equal to -1) when it detects end-of-file or error. To check robustly for end-of-file, do this:

int c = file.peek();
if (c == EOF) {
  if (file.eof())
    // end of file
  else
    // error
} else {
  // do something with 'c'
}

知道基础操作系统原语, read(2) ,只有当您尝试读取过去文件的结尾时才会发出EOF信号。因此,当您只读取最多文件中的最后一个字符时, file.eof()将不为真。换句话说, file.eof()为false并不意味着下一个读取操作将成功。

You should know that the underlying OS primitive, read(2), only signals EOF when you try to read past the end of the file. Therefore, file.eof() will not be true when you have merely read up to the last character in the file. In other words, file.eof() being false does not mean the next read operation will succeed.

这篇关于如何知道下一个字符是否是C ++中的EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆