c++ - 如何解析字符串 "(2 -59.0)"?

标签 c++

我如何解析像 "(x y)" 这样的字符串(例如:"(2 -59.0)"(11 1)) 转换成整数 x 和 float y?

最佳答案

主要是 C 背景,我特别喜欢 sscanf() 特别是当数据的格式与您的问题中描述的一样好时。但是,还有其他几种方法可以做到这一点。如果您想要纯 C++ 实现,我建议您查看 <sstream> 标题。

#include <cstdio>
#include <iostream>
#include <string>

int main() {
    int x;
    float y;

    std::string str = "(2 -59.0)";

    sscanf(str.c_str(), "(%d %f)", &x, &y);

    std::cout << "(" << x << " " << y << ")" << std::endl;
}

这产生

$ ./a.out
(2 -59)

关于c++ - 如何解析字符串 "(2 -59.0)"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32570558/

相关文章:

c++ - 为我将在 std::map 中使用的对象数组分配和释放内存的正确方法

c++ - 哪种数据结构更适合用于查找句子是否包含唯一字符?

c++ - 在抛出 'std::logic_error' what(): basic_string::_M_construct null 的实例后终止调用无效

c++ - 如何一次为一堆对象分配内存?

c++ - 在模板参数中使用时,type_trait<T>{} 中的 {} 的作用是什么?

C++类数组

c++ - 类模板的条件无效成员函数(隐式实例化有效;显式实例化失败)

c++ - 如何知道我的编译器如何编码 float 据?

c++ - 奇怪的 std::distance 输出

c++ - Qt moc 在头文件中实现?