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

How do I read in characters until the end (or right before the end) of a file?

我需要做的事情:

读取名为 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)将return用于读取的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 != '\'');