2015-05-05 29 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

相关问题