我如何解析像 "(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/