我需要做的:
读取名为 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/