2016-04-20 60 views
0

如何将字符串3 word 12 with word转换为int只包含数字312而不使用stoiC++?当我尝试使用它时,我的Codeblode给了我一个错误stoi is not a member of stdC++将字符和数字转换为字符串

预先感谢您!

+2

请发布您的代码,最好是[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。 –

+0

使用'-std = C++ 14'编译器开关,并将编译器更新为[mingw-w64](http://mingw-w64.org)(它自带的缺省值为废话) –

回答

1

通过该行并跳过非数字符号。并为数字使用-'0'转换和*10转换方式。 E.G .:

#include <stdio.h> 
#include <ctype.h> 
//or cctype to use isdigit() 
#include <string.h> 
//or cstring to use strlen() 

int main() 
{ 
    char str[] = "3 word 12 with word"; // can be any string 
    int result = 0; // to store resulting number 
    // begin of solution 
    for (int i = 0; i < strlen(str); i++) 
    { 
     if (isdigit(str[i])) 
     { 
      result *= 10; 
      result += str[i] - int('0'); 
     } 
    } 
    // end of solution 
    printf("%d\n", result); 
    return 0; 
} 
0

假设s是你的初始字符串。

int toInt(string s) { 
    string digits; 
    for(size_t i = 0; i < s.size(); i++) 
     if(s[i] >= '0' && s[i] <= '9') 
      digits.push_back(s[i]); 

    int res = 0; 
    for(size_t i = 0; i < digits.size(); i++) 
     res = res * 10 + digits[i] - '0'; 
    return res; 
} 

前导零不是问题。 但请注意,如果生成的digits字符串包含大数字,则可能会收到溢出。

1

VolAnd's answer中的想法相同。只是,因为这个问题被标记为c++,使用一些STL的东西。

#include <iostream> 
#include <numeric> 
#include <string> 
using namespace std; 

int main(){ 
    std::string input("3 word 12 with word"); 

    int num = std::accumulate(input.begin(), input.end(), 0, 
      [](int val, const char elem) { 
       if (isdigit(elem)) { 
        val = val*10 + (elem-'0'); 
       } 
       return val; 
     } 
    ); 

    std::cout << num << std::endl; 
    return 0; 
} 

看到http://en.cppreference.com/w/cpp/algorithm/accumulate

注意:如果你想允许负号它变得稍微更有趣....

而且在这一个使用boost::adaptors::filter(rng, pred)会很有趣,但略有矫枉过正;-)