2013-04-25 137 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);