用空格分隔字符串的最简单方法
Easiest way to separate a string by spaces?
我已经很久没有使用C++了,在我的空闲时间一直在使用Javascript,现在我不确定我到底记得什么。
基本上,我只需要通过查看空格将字符串分成几部分。
我看到的所有链接都是自制函数,但我本可以发誓有一种方法可以通过使用流来使用标准库来做到这一点,但同样,我很难回忆起它,我的谷歌结果也没有帮助。
请记住,它不是我从中获取的流,它只是一个字符串,例如"Bob Accountant 65 retired",我必须将字符串中的每个项目提取到它自己的数据字段中。我一直在搞乱ifstreams和ofstreams,但我什至不确定我在做什么,忘记了它的语法。
std::strtok
是C风格的方法。您可能正在考虑使用std::stringstream
,例如:
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::string input = "foo bar baz quxxnducks";
std::stringstream ss(input);
std::string word;
while (ss >> word) {
std::cout << word << 'n';
}
}
运行时,将显示:
foo
bar
baz
quxx
ducks
如果你想将数据从std::stringstream
(或任何类型的std::istream
,实际上)读入特定的数据类型,你可以按照@JerryCoffin的优秀建议,为你的数据类型重载流operator>>
:
#include <sstream>
#include <string>
#include <iostream>
struct Employee {
std::string name;
std::string title;
int age;
std::string status;
};
std::istream& operator>>(std::istream &is, Employee &e) {
return is >> e.name >> e.title >> e.age >> e.status;
}
int main() {
std::string input = "Bob Accountant 65 retired";
std::stringstream ss(input);
Employee e;
ss >> e;
std::cout << "Name: " << e.name
<< " Title: " << e.title
<< " Age: " << e.age
<< " Status: " << e.status
<< 'n';
}
您可以在没有显式循环的情况下执行此操作,如下所示:
string s = "Bob Accountant 65 retired";
vector<string> vs;
istringstream iss(s);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(vs));
std::copy
从在第三行创建的字符串流中读取所有内容,并将其推送到在第二行创建的向量中。
这是关于 ideone 的演示。
从外观上看,您正在尝试从字符串中读取逻辑记录。为此,我会做这样的事情:
struct record {
std::string name;
std::string position;
int age;
std::string status;
};
std::istream &operator>>(std::istream &is, record &r) {
return i >> r.name >> r.position >> r.age >> r.status;
}
这使您可以将数据从stringstream
读取到指定字段的record
。顺便说一下,它还允许您从其他类型的流中读取record
对象(例如,从使用 fstream
的文件)。
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- boost::variant - 对变体应用算术的最简单方法
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 从 txt 文件中读取数据的最简单方法
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 编写要在 Python 中使用的并行 C/C++ 模块的最简单方法
- 开放式颜色多边形表面的最简单方法
- 确定代码中当前程序集是否为 32/64 位的最简单方法
- 将unique_ptr存储在堆上的最简单方法是什么
- 使用 C# 获取 OpenGL 版本的最简单方法
- 在自定义 C/C++ 程序中获取 PPP0 接口 Tx/Rx 字节的最简单方法是什么?
- 为depth_first_search定义颜色图的最简单方法