字符串流未按预期工作
stringstream not working as expected
我正在尝试编写用于解析和处理文本文件的程序。在未能成功实现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
。
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- C++20字符串文本模板参数工作示例
- 将双精度值转换为 char 变量时字符串流如何工作
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- 为什么 C 样式字符串的工作空指针检查不?
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- 在 stl 中的字符串中擦除关键字的工作?
- scanf() 语句中"%*[^n]"的格式字符串指示什么?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- 使用 for 循环打印字符串数组无法正常工作 (C++)
- 字符串文字到 char 数组的转换如何在C++中实际工作
- 如何让我的构造函数和函数工作,以便我的 main() 能够同时显示字符串和 int 数据
- 如何使用字符串更改此插入功能以在链接列表中工作
- 如何与C 字符串中的非ASCII字符一起工作
- 读取进程内存无法正常工作,使用 UTF16 字符串
- strcpy() 和 strcat() 在 Turbo C++ 中无法正常工作(从字符串 litteral 初始化数组时
- C-字符串的获取线函数无法正常工作
- 这个右移是如何工作的:字符串流>>无符号的int>>无符号的int?
- 字符串的二进制搜索无法正常工作