我正在尝试将由空格分隔的字符串插入到字符串数组中, 而不 在 C++ 中使用向量。例如:
using namespace std;
int main() {
string line = "test one two three.";
string arr[4];
//codes here to put each word in string line into string array arr
for(int i = 0; i < 4; i++) {
cout << arr[i] << endl;
}
}
我希望输出为:
test
one
two
three.
我知道在 C++ 中已经有其他问题询问字符串 > 数组,但我找不到任何满足我的条件的答案:将字符串拆分为数组而不使用向量。
原文由 txp111030 发布,翻译遵循 CC BY-SA 4.0 许可协议
可以使用
std::stringstream
类(其构造函数将字符串作为参数)将字符串转换为流。构建完成后,您可以在其上使用>>
运算符(如基于常规文件的流),它将从中提取或 标记 单词: