我有一个格式为#########s###.## 的字符串 其中 #### 只是几个数字,第二部分通常是小数,但并非总是如此。
我需要将两个数字分开,并将它们设置为两个 double (或其他一些有效的数字类型。
我只能为此使用标准方法,因为运行它的服务器只有标准模块。
我目前可以使用 find 和 substr 获取第二 block ,但不知道如何获取第一 block 。我仍然没有做任何将第二部分更改为数字类型的事情,但希望这会容易得多。
这是我所拥有的:
string symbol,pieces;
fin >> pieces; //pieces is a string of the type i mentioned #####s###.##
unsigned pos;
pos = pieces.find("s");
string capitals = pieces.substr(pos+1);
cout << "Price of stock " << symbol << " is " << capitals << endl;
最佳答案
istringstream
让它变得简单。
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char* argv[]) {
std::string input("123456789s123.45");
std::istringstream output(input);
double part1;
double part2;
output >> part1;
char c;
// Throw away the "s"
output >> c;
output >> part2;
std::cout << part1 << ", " << part2 << std::endl;
return 0;
}
关于c++ - 将字符串解析为两个 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16222997/