我在Java中经历了十年之后回归C++,现在我已经坚持了两个星期了,我看到很多有getline问题的帖子,这些让我添加了很多“cout”试图找到确切的错误,我已经发现了错误,失败和eof位,但仍然存在相同的问题.getline不填充字符串或进入while循环。 不知道如果它很重要,但我在NetBeans中编写Win7 PC和编译/运行在rasberry pi(运行raspbian(Debian,我认为))C++ getline失败,并显示“Success”:-(
我想要做的就是读取使用getline的简单文本文件!应该是基本的('scuse the pun :-)) 我试图用Unix和ASCII行结尾(0x0A和0x0D0A)创建文本文件 - mad没有区别。我使用创建文本文件的相同用户标识运行程序,因此没有权限问题。
Getline设置失败位(仅...不是eof),但是perror报告“成功”,并且在“工作”中我没有得到任何数据。
下面是导致错误的大部分类 - 带有许多调试注释。 “theFile”只是一个fstream('未来版本中的cos可能想将其打开以用于输出)。但是,在这里,你可以从输出中看到,我绝对使用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所以任何帮助将真正感激。
您的问题未能满足[mcve]的要求。您正在寻找的帮助是创建[mcve]以包含在您的问题中的说明。 –
看起来过于复杂,与语言风格相反。你是否打算首先查找一个例子来熟悉“C++中的事情是如何完成的”? –
可能重复[逐行读取文件](https://stackoverflow.com/questions/7868936/read-file-line-by-line) –