2015-05-05 26 views
2

我在從C++中的字符串中提取signed int時遇到了問題。 假設我有一個字符串images1234,我怎麼能從字符串中提取1234而不知道C++中最後一個非數字字符的位置。從包含其他字符的字符串中提取尾部int

僅供參考,我嘗試stringstream以及lexical_cast由其他人通過帖子建議,但stringstream返回0,而lexical_cast停止工作。

int main() 
{ 
    string virtuallive("Images1234"); 
    //stringstream output(virtuallive.c_str()); 
    //int i = stoi(virtuallive); 
    //stringstream output(virtuallive); 
    int i; 
    i = boost::lexical_cast<int>(virtuallive.c_str()); 
    //output >> i; 
    cout << i << endl; 
    return 0; 
} 

回答

1

另一種可能性是把字符串轉換爲stringstream,然後從流讀取數(灌輸與除數字爲白色分類一切語言環境的流之後空間)。

// First the desired facet: 
struct digits_only: std::ctype<char> { 
    digits_only(): std::ctype<char>(get_table()) {} 

    static std::ctype_base::mask const* get_table() { 
     // everything is white-space: 
     static std::vector<std::ctype_base::mask> 
      rc(std::ctype<char>::table_size,std::ctype_base::space); 

     // except digits, which are digits 
     std::fill(&rc['0'], &rc['9'], std::ctype_base::digit); 

     // and '.', which we'll call punctuation: 
     rc['.'] = std::ctype_base::punct; 
     return &rc[0]; 
    } 
}; 

然後代碼讀取數據:

std::istringstream virtuallive("Images1234"); 
virtuallive.imbue(locale(locale(), new digits_only); 

int number; 

// Since we classify the letters as white space, the stream will ignore them. 
// We can just read the number as if nothing else were there: 
virtuallive >> number; 

主要在流中包含數據的大量這種技術是有用的,你想所有數據在流是以相同的方式解釋(例如,只讀數字,不管它可能包含什麼)。

+0

嗨,傑裏,非常感謝您的迴應,考慮到我在C++中是一個新手,需要一些時間來正確地消化代碼,以後會嘗試並理解代碼。真的很感謝你的幫助 – vincent911001

2

我怎麼能提取字符串中的1234不知道C++中的最後一個非數字字符的位置?

你不行。但位置並不難找:

auto last_non_numeric = input.find_last_not_of("1234567890"); 
char* endp = &input[0]; 
if (last_non_numeric != std::string::npos) 
    endp += last_non_numeric + 1; 
if (*endp) { /* FAILURE, no number on the end */ } 
auto i = strtol(endp, &endp, 10); 
if (*endp) {/* weird FAILURE, maybe the number was really HUGE and couldn't convert */} 
+0

嗨,本,它真的有用。我也嘗試了Thorney的另一個解決方案,但結果返回0.感謝您的指導,感謝您的幫助。 – vincent911001

相關問題