【问题标题】:How using with istringstream in c++? [closed]如何在 C++ 中使用 istringstream? [关闭]
【发布时间】:2017-08-23 17:35:00
【问题描述】:

我在 C++ 中寻找分割空格的函数。我在互联网上找到了这个代码。我想知道是怎么说的。

  string line;
  istringstream buf(line);
  istream_iterator<string> beg(buf), end;
  vector<string> tokens(beg, end);
  return tokens;

【问题讨论】:

  • 更具体;我相信有很多文章解释它。 SO 不是为您提供代码解释的网站。
  • 为什么我需要 istringstream?我想用空格分割
  • edit您的问题表明您的确切目的。
  • 我编辑了我的帖子
  • 请清楚并检查您是否可以在任何其他堆栈交换网站上找到此内容。

标签: c++ string stream


【解决方案1】:

见:

#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>

std::vector<std::string> SplitByWhiteSpace(std::string stringToSplit)
{
    std::istringstream buf(stringToSplit);
    std::istream_iterator<std::string> beg(buf), end;
    return std::vector<std::string>(beg, end);
}

int main() {
    std::vector<std::string> tokens = SplitByWhiteSpace("Hello World!");

    for (std::size_t i = 0; i < tokens.size(); ++i)
    {
        std::cout<<tokens[i]<<"\n";
    }

    return 0;
}

该代码通过空格分割字符串并返回向量中的所有标记。然后,您可以打印向量中的所有标记。

几乎和做的一样(结果相同,技术不同):

std::vector<std::string> SplitByWhiteSpace(std::string stringToSplit)
{
    std::string word;
    std::vector<std::string> tokens;
    std::istringstream buf(stringToSplit);

    while (buf >> word)
    {
        tokens.push_back(word);
    }

    return tokens;
}

【讨论】:

  • 我试图了解分裂发生在哪里?当我写 std::vector<:string>(beg, end); ??
猜你喜欢
  • 2012-02-17
  • 2019-04-28
  • 2014-11-04
  • 1970-01-01
  • 2013-05-11
  • 2011-02-15
  • 2014-08-03
相关资源
最近更新 更多