c++ - ifstream object.eof() 不工作

标签 c++

我想我可能需要为我的 while 条件使用 bool 值 bValue = false:

char cArray[ 100 ] = "";
ifstream object;
cout << "Enter full path name: ";
cin.getline( cArray, 100 );
if ( !object ) return -1   // Path is not valid? This statement executes why?

ifstream object.open( cArray, 100 );

// read the contents of a text file until we hit eof.
while ( !object.eof() )
{
// parse the file here

}

为什么我不能输入文本文件的完整路径名?

可能是因为eof。它们的语法是可以模拟 eof 的 bool 语句吗?

我可以:

while ( !object == true )
{
// parase contents of file
}

最佳答案

请你和其他人注意,读取文本文件的正确方法不需要使用 eof()、good()、bad() 或 indifferent() 函数(好吧,我做了最后一个向上)。在 C 中也是如此(使用 fgets()、feof() 等)。基本上,这些标志只会在您尝试使用 getline() 之类的函数读取内容后设置。测试读取函数要简单得多,也更有可能是正确的,比如 getline() 实际上已经直接读取了一些东西。

未测试 - 我正在升级我的编译器:

#include <iostream>
#include <fstream>
#include <string>
using namespacr std;

imt main() {

   string filename;
   getline( cin, filename );

   ifstream ifs( filename.c_str() );
   if ( ! ifs.is_open() ) {
       // error
   }

   string line;
   while( getline( ifs, line ) ) {
       // do something with line
   }
}

关于c++ - ifstream object.eof() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/730910/

相关文章:

c++ - 带有文件信息的 CaptureStackBackTrace

c++ - 使用重定向在 C++ 中打印到文件是否比使用对流 cout 更快?

c++ - 指针 - 在 C++ 中返回本地引用

c++ - 有没有一种方法可以初始化一个不涉及编写构造函数的新结构变量?

c++ - CRTP - 计算单个类和总计数

c++ - 使用不同的类类型重复 Boost 单元测试

c++ - 如何将 double 转换为字符串?

c++ - 成员函数之外的封闭类的定义中需要默认成员初始值设定项

c++ - 具有继承的全局类比较

c++ - 二维 C 样式数组崩溃