c++ - 如何读入文件的末尾(或刚好在末尾之前)的字符?

标签 c++ ifstream

我需要做的:

读取名为 textFile 的 ifstream 类型的文本文件,每次读取一个字符 ch,直到 ch 等于单引号 '。如果 ch 永远不等于引号,则打印失败并跳出循环。

//read a character from the file into ch;
textFile.get(ch);
            // while ch is not a single quote
            while (ch != '\'')
            {
                //read in another character
                textFile.get(c);

                if (textFile.peek(), textFile.eof())
                  {
                     cout << "FAIL";
                     break;
                  }
            }

我正在读取的 textFile.txt 没有单引号,因此输出应该是 FAIL。

但是当我打印它时,它打印了两次失败。感谢任何帮助

最佳答案

ifstream::get(char& c)会返回用于读取的ifstream对象,可以作为读取是否成功的条件。使用它。

你的代码应该是这样的:

char c, ch;
// while ch is not a single quote
do
{
    //read in another character
    // you can use ch directly here and remove the assignment ch = c; below if you want
    if(!textFile.get(c))
    {
       cout << "FAIL";
       break;
    }
    ch = c;
} while(ch != '\'');

关于c++ - 如何读入文件的末尾(或刚好在末尾之前)的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35952149/

相关文章:

c++ - 在 C++ 中搜索 CString

c++ - 具有#define值的std::compare_exchange int

c++ - std::queue 内存消耗导致内存泄漏 - C++?

C++虚拟克隆方法,异常继承

c++ - 从文本文件中读取不同数量的值到数组中

c++ - 如果标准 C++ 库函数为 char 值返回 int,是否需要强制转换?

c++ - `new/malloc` 应该是 `delete/free` 的那个?

C++ Map基于变量键返回类对象

c++ - 用C++保存文件没有写入数据

c++ - ifstream.eof() 在 C++ 中未评估为真