2013-04-25 151 views
2

我有一个字符串,格式为######### s ###。## 其中####只是几个数字,第二个通常是小数,但并不总是。将一个字符串解析为两个双重字符串

我需要打散两件数,并将其设置为两个双打(或一些其他有效的数字类型。

我只能用标准方法对于这一点,作为服务器它正在上只有运行标准模块

我目前可以用find和substr来抓取第二块,但是不知道如何得到第一块,我还没有做任何改变第二块成数值类型的东西,但是希望这很容易。

这是我有:

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; 
+1

如何服用长度的字符串'pos'从指数0开始? – 2013-04-25 19:22:16

回答

1

,你的愿望此代码将拆分string并将其转换为double,它可以很容易地改变转换成float还有:

#include <iostream> 
#include <sstream> 
#include <string> 
#include <stdexcept> 

class BadConversion : public std::runtime_error { 
public: 
    BadConversion(std::string const& s) 
    : std::runtime_error(s) 
    { } 
}; 

inline double convertToDouble(std::string const& s, 
           bool failIfLeftoverChars = true) 
{ 
    std::istringstream i(s); 
    double x; 
    char c; 
    if (!(i >> x) || (failIfLeftoverChars && i.get(c))) 
    throw BadConversion("convertToDouble(\"" + s + "\")"); 
    return x; 
} 

int main() 
{ 
    std::string symbol,pieces; 

    std::cin >> pieces; //pieces is a string of the type i mentioned #####s###.## 
    unsigned pos; 
    pos = pieces.find("s"); 
    std::string first = pieces.substr(0, pos); 
    std::string second = pieces.substr(pos + 1); 
    std::cout << "first: " << first << " second " << second << std::endl; 
    double d1 = convertToDouble(first), d2 = convertToDouble(second) ; 
    std::cout << d1 << " " << d2 << std::endl ; 
} 

仅供参考,我从我的previous answers中选择了一个转换代码。

2

您可以调用substr时偏移沿指定计数:

string first = pieces.substr(0, pos); 
string second = pieces.substr(pos + 1); 
2

你可以做同样的事情,你做第二部分:

unsigned pos; 
pos = pieces.find("s"); 
string firstPart = pieces.substr(0,pos); 
1

抓住了第件很容易:

string firstpiece = pieces.substr(0, pos); 

至于转换为n umeric类型,我觉得sscanf()特别有用的是:

#include <cstdio> 

std::string pieces; 
fin >> pieces; //pieces is a string of the type i mentioned #####s###.## 

double firstpiece = 0.0, capitals = 0.0; 
std::sscanf(pieces.c_str() "%lfs%lf", &firstpiece, &capitals); 
... 
3

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; 
} 
0

一些永世会抱怨,这不是C++ - 年,但,这是合法的C++


    char * in = "1234s23.93"; 
    char * endptr; 
    double d1 = strtod(in,&endptr); 
    in = endptr + 1; 
    double d2 = strtod(in, &endptr);