来自 istringstream 的五倍输出

Fivefold output from istringstream

本文关键字:五倍 输出 istringstream 来自      更新时间:2023-10-16

我想在检测到某个子字符串后输出每一行。不知何故,我得到了iss五倍的输出.这是我的代码:

//load all data from txt
string data;
std::ifstream infile("SavedData.txt");
while (std::getline(infile, data)) {
std::istringstream iss(data);
string d;
while (iss >> d) {
//extract substring
unsigned firstBracket = data.find("(");
unsigned lastBracket = data.find(")");
string coordSynth = data.substr(firstBracket + 1, lastBracket - firstBracket - 1);
cout << coordSynth << endl;
}
}

现在的输出是这样的:

0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -314.3
0.0, 45.0, -314.3
0.0, 45.0, -314.3
0.0, 45.0, -314.3
0.0, 45.0, -314.3
etc.

其实我只是想要

0.0, 45.0, -390.0
0.0, 45.0, -314.3
0.0, 45.0, -277.3
etc.

不,在 txt 文件中没有重复。此文件如下所示:

0001(0.0, 45.0, -390.0).png 
0003(0.0, 45.0, -314.3).png 
0007(0.0, 45.0, -277.3).png (and so on...)

你在这里的问题是

unsigned firstBracket = data.find("(");
unsigned lastBracket = data.find(")");
string coordSynth = data.substr(firstBracket + 1, lastBracket - firstBracket - 1);
cout << coordSynth << endl;

这是从0001(0.0, 45.0, -390.0).png中获取0.0, 45.0, -390.0的逻辑,它位于一个你甚至没有做任何事情的while循环中。 该循环将为每行输入执行 5 次(因为有五个"子字符串"(,因此您将获得 5 个输出。 您需要做的就是摆脱 while 循环,因为您没有对行中包含的单个字符串执行任何操作。 这给了你类似的东西

int main() 
{   
std::string data;
std::istringstream infile("0001(0.0, 45.0, -390.0).pngn0003(0.0, 45.0, -314.3).pngn0007(0.0, 45.0, -277.3).pngn");
while (std::getline(infile, data)) {
std::istringstream iss(data);
std::string d;
//extract substring
unsigned firstBracket = data.find("(");
unsigned lastBracket = data.find(")");
std::string coordSynth = data.substr(firstBracket + 1, lastBracket - firstBracket - 1);
std::cout << coordSynth << std::endl;
}
}