我正在尝试阅读格式不正确的文本文件,也许我会以错误的方式解决这个问题,但基于getline文档,它听起来像是会拉取值,直到值不是分隔符值(' ',就我而言):
“如果找到分隔符,则将其提取并丢弃,即它 没有存储,下一个输入操作将在它之后开始。如果你 不希望提取此字符,可以使用member 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();
}
啊,抱歉不包括代码。
答案 0 :(得分:1)
如果您在任何时候使用空格作为分隔符,那么getline将返回任何有分隔符的内容。如果文件在任何其他字符之前连续有5个空格,例如你现在必须调用getline 6次。
也许使用默认换行符'\n'
?
编辑:之前没有看过代码。也许重新构建代码以读取行,然后在每行使用find
和substr
来搜索关键字?代码更简单,循环更少。没有理由从文件中读取只输出到您随后读取的字符串流。
答案 1 :(得分:1)
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
manipulator:
istringstream isn(line);
isn >> ws;
// ...
答案 2 :(得分:1)
我认为我正在阅读的输出文本文件有尾随空格,它们只是被放入流中,所以我对发生的事情感到很困惑。我只是在每一行的末尾使用.str(“”)来重置我当前的流,事情很精彩。感谢所有帮助人员。