【问题标题】:Split String to Vector with Whitespaces c++ error使用空格将字符串拆分为向量 c++ 错误
【发布时间】:2016-11-29 18:44:18
【问题描述】:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;


vector<string> split_string(string s)
{
string buf;
stringstream ss(s);

vector<string> tokens;

while (ss >> buf)
    tokens.push_back(buf);

return tokens;
}


int main()
{
   cout << split_string("Alpha Beta Gamma");
}

当我尝试使用空格将字符串拆分为向量时,我无法打印出我的解决方案。

我不允许我使用 std::cout 但在我的函数中给出了返回值

为什么我不能那样使用它?我该如何解决这个问题?

【问题讨论】:

  • std::vector 没有重载运算符
  • 这是和this one一样的赋值吗?

标签: c++ string vector split


【解决方案1】:

std::cout 不能带向量,你需要遍历容器并分别打印每个元素,尝试使用这样的东西:

int main()
{
    string originalString = "Alpha Beta Gamma";  

    for (const auto& str : split_string(originalString))
        cout << str << '\n';

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2014-09-16
    相关资源
    最近更新 更多