使用 find() 将一行拆分为标记
Splitting a line into token with find()
我想拆分这一行:
cmd1; cmd2; cmd3
分成 3 个字符串,我将库存到一个列表中。
cmd1
cmd2
cmd3
所以我做了这个代码:
main.cpp
#include <string>
#include <iostream>
#include <list>
int main()
{
std::string line("cmd1; cmd2; cmd3");
std::list<std::string> l;
size_t pos = 0;
size_t ex_pos = 0;
while ((pos = line.find(';', ex_pos)) != std::string::npos)
{
l.push_back(line.substr(ex_pos, pos));
ex_pos = pos + 2;
}
l.push_back(line.substr(ex_pos, pos));
for (std::list<std::string>::iterator it = l.begin(); it != l.end(); ++it)
{
std::cout << *it << std::endl;
}
return (0);
}
但我不知道为什么它会返回我:
cmd1
cmd2; cmd3
cmd3
substr
的第二个参数不是要复制的 lat 字符索引。它是目标子字符串的长度。
l.push_back(line.substr(ex_pos, pos-ex_pos));
http://www.cplusplus.com/reference/string/string/substr/
std::basic_string::substr 的第二个参数需要一个长度,指示从 start_pos 开始的子字符串的长度。
string substr (size_t pos = 0, size_t len = npos) const;
所以,你实际上应该替换
l.push_back(line.substr(ex_pos, pos));
跟
l.push_back(line.substr(ex_pos, pos - ex_pos));
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- C++将向量的向量拆分为向量的N个子向量
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- OpenCV 4.1.2 - 从网络摄像头获取帧并将其拆分
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 使用 C++ 将命令行参数拆分为参数/向量
- 使用 std::regex 拆分一行并丢弃空元素
- 使用 find() 将一行拆分为标记
- c++如何将文本文件中的一行拆分为两行,然后将每行存储到两个不同的数组中
- 如何在C++中读取文件并拆分每一行
- 根据关键字拆分一行(有拼写错误)
- 我将如何使用 cin 读取一行用户输入,将该行拆分为空格,并将这些标记存储到字符串数组中