将string转换为int使用sstream

时间:2013-09-21 11:24:49

标签: c++ string int sstream

我们希望使用 sstream 将字符串转换为int。

但是我们不知道我们的字符串是否有整数,例如它可以是 “hello 200” ,我们想要 200 在那,或者它可以 “你好” 并且没有解决方案

当我们在字符串中只有一个整数时,我有这个代码:

inline int string_to_int(string s)
{
    stringstream ss(s);
    int x;
    ss >> x;
    return x;
}

现在,如果s =“你好200!”或者s =“你好”,我们该怎么做?

3 个答案:

答案 0 :(得分:4)

在字符串中的第一个整数之前忽略错误输入的简单可能性:

bool string_to_int(string str, int &x)
{
    istringstream ss(str);

    while (!ss.eof())
    {
       if (ss >> x)
           return true;

       ss.clear();
       ss.ignore();
    }
    return false; // There is no integer!
}

答案 1 :(得分:1)

根据有限状态机编写解析器并根据需要更正任何输入:

int extract_int_from_string(const char* s) {
   const char* h = s;
   while( *h ) {
      if( isdigit(*h) )
         return atoi(h);
      h+=1;
   }
   return 0;

} ... int i = extract_int_from_string(“hello 100”);

答案 2 :(得分:0)

 //You can use the following function to get the integer part in your string...
    string findDigits(string s){
    string digits="";
    int len=s.length();
    for(int i=0;i<len;i++){
        if(s.at(i)>='0' && s.at(i)<='9')
        digits+=s[i];}
     return digits;}

// and call the above function inside this function below...
    int string_to_int(string s){
    string digits=findDigits(s);
    stringstream ss(digits);
    int x;
    ss >> x;
    return x;}