c++ - 使用 boost 生成适当数量的 token

标签 c++ boost

我有如下代码

 std::string some_string = "-0.003  79350   -0.267  147";
 boost::algorithm::trim (some_string);
 //std::cout << some_string << std::endl;
 boost::tokenizer<> tok( some_string );
 const auto n = std::distance( tok.begin(), tok.end() );
 std::cout << n << std::endl;

我希望 token 的数量为 4,但它给出了 6。任何建议,将不胜感激。谢谢。

最佳答案

不需要boost,也更正确。

假设你真的想解析数字更正确

Live On Coliru

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

int main() {
    std::istringstream some_string ( "-0.003  79350   -0.267  147");
    std::cout << std::distance(std::istream_iterator<double>(some_string), {});
}

更新

如果您想保留标记,而不仅仅是解析数字:

Live On Coliru

istringstream s("-0.003  79350   -0.267  147");

vector<string> vec(istream_iterator<string>(s), {});

cout << vec.size();

关于c++ - 使用 boost 生成适当数量的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388548/

相关文章:

c++ - Linux: C++:/usr/bin/ld: 找不到 -llibboost_serialization

c++ - 为什么 cout 在与三元和 int 一起使用时打印 char 的 ascii 值?

c++ - int* 的默认值是 NULL 吗?

c++ - std::vector(InputIterator first, InputIterator last) 是线性时间复杂度吗?

c++ - 删除 C++ 模板类中的性能警告

c++ - Boost.Fusion 定义结构数组成员

python - 在 Boost Python 中使用带有 std::wstring 的 C++ 函数的 Unicode

c++ - QT TCP套接字连接异常。实参太多

c++ - 从继承的类实例调用静态成员

c++ - 与 C++ 静态库的链接问题