为什么istream::getline()返回这么多次(什么都没有)
Why istream::getline() returns so many times (with nothing)
我试图阅读一个格式不好的文本文件,也许我是在错误的方式,但根据getline文档,它听起来像它会拉值,直到值不是分隔符值(' ',在我的情况下):
"如果找到分隔符,则提取并丢弃它,即不存储,下一个输入操作将在它之后开始。如果你如果不想提取此字符,可以使用成员get代替。"
但是由于某种原因,它多次没有返回任何结果。参见第604-607行,我输出中的所有逗号都是getline的返回。有人能告诉我为什么它返回空白6次之前,它来的值?文本文件的值前只包含一个空格。提前感谢。:)
相关截图:http://j.drhu.me/2011-09-07_1317.png
#include <iostream>
#include <fstream>
#include <string>
void CMuscleModel::LoadOpParams()
{
int i, j;
ifstream param("params.txt", ios::in);
if (param.is_open())
{
stringstream iss, isn;
string line, word;
i=0; j=0;
while (getline(param,line))
{
isn.clear();
isn << line;
if(i>27){
while (getline(isn,word,' ')) {
//LGma[i][j]=atof(word.c_str());
if(word == "SM"){
getline(param,line);
cout << line << endl << endl;
isn.clear(); isn << line;
getline(isn,word,' ');
int junk=0;
while (atof(word.c_str())==0){
junk++;
getline(isn,word,' ');
}
cout << atof(word.c_str()) << ", " << junk << endl;
}
if(word == "ST"){
cout << word << endl;
}
if(word == "BFL"){
cout << word << endl;
}
if(word == "BFS"){
cout << word << endl;
}
if(word == "MG"){
cout << word << endl;
}
if(word == "LG"){
cout << word << endl;
}
if(word == "RF"){
cout << word << endl;
}
if(word == "VM"){
cout << word << endl;
}
if(word == "VL"){
cout << word << endl;
}
if(word == "VI"){
cout << word << endl;
}
j++;
}
}
j=0; i++;
isn.clear();
}
}
param.close();
}
啊,抱歉没有包含代码
如果在任何时候使用空格作为分隔符,getline将返回分隔符之前的所有内容。例如,如果文件在任何其他字符之前的一行中有5个空格,那么您现在必须调用getline 6次。
可以使用默认换行符代替'n'
?
Edit:之前没有看到代码。也许重构代码以读取行,然后在每行上使用find
和substr
来搜索关键字?将是更简单的代码和更少的循环。没有理由只从文件中读取输出到字符串流,然后从。
与std::stringstream
的双向I/O确实是模糊的。我建议你用一种稍微不同的方式。
ifstream param("params.txt", ios::in);
if (param.is_open())
{
stringstream iss;
string line, word;
i=0; j=0;
while (getline(param,line))
{
istringstream isn(line);
// ...
}
}
这将创建一个具有干净状态的新字符串流,并包含每次从文件中读取的行内容。如果您真的想重用实例来读取多行标记,我建议您使用.str(line)
语法,而不是.clear()
和operator<<
。
如果要清除每行开头的空白,可以使用std::ws
操纵符:
istringstream isn(line);
isn >> ws;
// ...
我认为我正在读取的输出文本文件有尾随空格,它们刚刚被放入流中,所以我真的很困惑发生了什么。我只是在每行末尾使用.str(")来重置当前流,结果非常好。谢谢大家的帮助。
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- "friend istream & operator >> (istream &, class_name &) ;"是什么意思?
- getline 和 std::istream::operator>>() 有什么区别?
- 函数int get()和istream&get(char&c)有什么区别
- istream中发生了什么隐式转换?
- 还有什么比使用istream eof更好的方法来读取文件直到它结束呢?
- 为什么istream::getline()返回这么多次(什么都没有)