如何解析字符串“(2 -59.0)”?

时间:2015-09-14 17:32:43

标签: c++

如何将"(x y)"(例如:"(2 -59.0)"(11 1))等字符串解析为整数x和浮点y

1 个答案:

答案 0 :(得分:0)

来自主要的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)