字符串流未按预期工作

stringstream not working as expected

本文关键字:工作 字符串      更新时间:2023-10-16

我正在尝试编写用于解析和处理文本文件的程序。在未能成功实现sscanf后,我决定尝试字符串流

我有一个字符串向量,包含用空格分隔的数据,比如:

some_string another_string yet_another_string VARIABLE_string_NO_1下一个字符串

我写了代码,预期结果是:

Counter: 4
Variable number 1 : VARIABLE_STRING_NO_1
Variable number 2 : VARIABLE_STRING_NO_2
Variable number 3 : VARIABLE_STRING_NO_3
Variable number 4 : VARIABLE_STRING_NO_4

但我得到的却是:

Counter: 4
Variable number 1 : VARIABLE_STRING_NO_1
Variable number 2 : VARIABLE_STRING_NO_1
Variable number 3 : VARIABLE_STRING_NO_1
Variable number 4 : VARIABLE_STRING_NO_1

有人能把我推向正确的方向吗?(例如,使用其他容器代替矢量,将方法更改为…等)

此外,如果VARIABLE_STRING包含两个子字符串,中间有空格,该怎么办?这在我的数据中是可能的。

样本代码:

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<string> vectorOfLines, vectorOfData;
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_1 next_string");
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_2 next_string");
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_3 next_string");
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_4 next_string");
string data = "", trash = "";
stringstream token;
int counter = 0;
for( int i = 0; i < (int)vectorOfLines.size(); i++ )
{
token << vectorOfLines.at(i);
token >> trash >> trash >> trash >> data >> trash;
vectorOfData.push_back(data);                       //  wrong method here?
counter++;                                          //  counter to test if for iterates expected times
}
cout << "Counter: " << counter << endl;
for( int i = 0; i < (int)vectorOfData.size(); i++ )
{
cout << "Variable number " << i + 1 << " : " << vectorOfData.at(i) << endl;
}
return 0;
}

请原谅我的新手问题,但在过去5天里尝试了不同的方法后,我开始咒骂,并对继续学习感到沮丧
是的,我对C++很陌生
我已经成功地用PHP完成了同样的程序(在这方面我也是个新手),而且C++似乎更难做。

您想在读取单个字符串后重置字符串流。从外观上看,您正在使用的字符串流将进入失败状态。在这一点上,它不会排除任何进一步的输入,直到状态得到clear()。此外,您应该始终验证您的阅读是否成功。也就是说,我会像这样开始你的循环:

token.clear();
token.str(vectorOfLines[i]);
if (token >> trash >> trash >> trash >> data >> trash) {
process(data);
}
else {
std::cerr << "failed to read '" << vectorOfLines[i] << "n";
}

我也会使用std::istringstream