ifstream object.eof()不工作 [英] ifstream object.eof() not working

查看:126
本文介绍了ifstream object.eof()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  char cArray [100] = ; 
ifstream object
cout<< 输入完整路径名:;
cin.getline(cArray,100);
if(!object)return -1 //路径无效?这个语句执行为什么?

ifstream object.open(cArray,100);

//读取文本文件的内容,直到我们点击eof。
while(!object.eof())
{
//解析这里的文件

}
pre>

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



这可能是因为eof。



可以有:

 

code> while(!object == true)
{
//文件的parase内容
}


解决方案

请大家和其他人一起注意,读取文本文件的正确方法不需要使用eof() (),bad()或indifferent()函数(OK,我做了最后一个)。在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()){
//错误
}

string行;
while(getline(ifs,line)){
//使用行
执行操作}
}


I think i might need to use a boolean bValue = false for my while condition:

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

}

Why can i not enter the full path name of the text file?

It might be because of the eof. Is their syntax for a boolean statement that can emulate eof?

Can i have:

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

解决方案

Please will you and everyone else note that the correct way to read a text file does NOT require the use of the eof(), good(), bad() or indifferent() functions (OK, I made the last one up). The same is true in C (with fgets(), feof() et al). Basically, these flags will only be set AFTER you have attempted to read something, with a function like getline(). It is much simpler and more likely to be correct to test that read functions, like getline() have actually read something directly.

Not tested - I'm upgrading my compiler:

#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
   }
}

这篇关于ifstream object.eof()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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