C++获取线失败,并显示"Success" :-(

C++ getline fails with "Success" :-(

本文关键字:Success 显示 获取 失败 C++      更新时间:2023-10-16

在Java工作了十年后,我回到了C++,这已经让我坚持了两个星期。我看过很多关于getline问题的帖子,这些帖子导致我添加了许多"cout",试图找出确切的问题所在。我已经发现了坏的,失败的和eof位,但仍然有同样的问题。getline 不会填充字符串或进入 while 循环。 不知道这是否重要,但我正在 Netbeans 的 Win7 PC 上编码并在树莓派上编译/运行(运行 raspbian(我认为是 Debian((。

我要做的就是使用 getline 读取一个简单的文本文件!应该是基本的('搜索双关语:-(( 我尝试创建同时带有 Unix 和 ASCII 行尾(0x0A 和 0x0D0A(的文本文件 - 没有区别。我使用创建文本文件的相同用户ID运行该程序,因此没有权限问题。

Getline 设置故障位(仅...不是 eof(,但错误报告"成功",我在"工作"中没有得到任何数据。

以下是导致错误的大多数类 - 具有许多调试注释。"theFile"只是一个流('因为在未来的版本中,我可能想打开它进行输出(。但是在这里,正如您从输出中看到的那样,我肯定会使用 ios::in 打开文件。"问题"发生在 getValue 成员函数中的 getline 循环(从未输入(中。 我没有包含构造函数,但它只将几个标志设置为 false。调用方(MJAppl(只是调用MJConfigFile::getValue("log_dir",false(。

string MJConfigFile::getValue ( string in_key, bool in_restart ) {
bool   found   = false ;
string work    , ret   ;
int    key_len = in_key.length() , loop_count = 0 ;
//char   workbuf [ 200 ] ;
cout << "MJConfigFile::getValue entry for key " << in_key << " n" ;
cout << "File name is " << getFName () << "n" ;
if ( in_restart || !openForInput ) {
theFile . close () ;
open ( false ) ;        
}
if ( theFile . is_open ()) {
cout << "File " << fullFileName << " is open." << "n";
} else {
perror ( "Error while opening file " ) ;
}
while ( getline ( theFile, work )) {
if (loop_count++ > 5 ) return "Stopped n" ;
cout << "Line '" << work << "'n";
if ( in_key.compare ( work ) == 0 ) {
ret = work.substr ( key_len + 1 ) ;
break ;
}
}
perror ( "Error reading file. " ) ;
cout << "Line after loop '" << work << "'n";
if ( theFile.bad() | theFile.fail() | theFile.eof()) {
if ( theFile . bad () ) cout << "Bad  file." << endl ;
if ( theFile . fail() ) cout << "Fail file." << endl ;
if ( theFile . eof () ) cout << "eof  file." << endl ;
}
return ret ;
}
void MJConfigFile::open () {
this -> open ( false ) ;
}
void MJConfigFile::open ( bool in_for_output ) {    
if ( in_for_output ) {
theFile . open ( fullFileName.c_str (), ios::out ) ;
if ( theFile . is_open ()) {
openForOutput = true ;
cout << "File is open for output. n" ;
}
} else {
theFile . open ( fullFileName.c_str (), ios::in ) ;
if ( theFile . is_open ()) { 
openForInput  = true ;
cout << "File is open for input. n" ;
}
}    
if ( openForInput || openForOutput ) {
exists   = true ;
}
}

下面是运行的示例输出:

In default MJConfigFile constructor
File is open for input.
MJAppl.readConfigFile() entry.
File is open for input.
MJConfigFile::getValue entry for key log_dir
File name is /mjmaint/MJApplCfg/MJApplCfg.cfg
File /mjmaint/MJApplCfg/MJApplCfg.cfg is open.
Error reading file. : Success
Line after loop ''
Fail file.
logdir is
0

下面是一个示例输入文件:

Aaaaaa
Bbbbbb
Cccccc

我几乎准备放弃并回到Java,所以任何帮助将不胜感激。

以防万一有人再次遇到这组相同的特殊失败/成功条件,问题是我在同一个流上调用了两次打开。打开似乎成功,但 getline 无法运行,因为流的失败位已设置。谢谢伊戈尔。