gpt4 book ai didi

c++ - 为什么 istream::getline() 返回这么多次(什么都没有)

转载 作者:行者123 更新时间:2023-11-30 02:07:56 24 4
gpt4 key购买 nike

我正在尝试读取一个格式不正确的文本文件,也许我以错误的方式解决这个问题,但根据 getline 文档,它听起来像是会提取值,直到值不是分隔符值 (' ',就我而言):

"If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it. If you don't want this character to be extracted, you can use member get instead."

但由于某种原因,它多次返回任何内容。请参阅第 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'

编辑:之前没有看到代码。也许重组您的代码以读取行,然后在每一行上结合使用 findsubstr 来搜索您的关键字?会更简单的代码和更少的循环。没有理由只从文件中读取输出到您随后从中读取的字符串流。

关于c++ - 为什么 istream::getline() 返回这么多次(什么都没有),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7338045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com