简体   繁体   中英

C++ Clean String to int cast

As far as i know, the common way in c++ to cast a String into a int is to use sstream:

   std::string inputString = "12 34";
   std::istringstream istr(inputString);
   int i1, i2;
   istr >> i1 >> i2;

But if I want to make sure, that my code works for any input, the problem is to decide between the input of a string or 0:

   std::string inputString = "TEXT 0";
   std::istringstream istr(inputString);
   int i1, i2;
   istr >> i1 >> i2;
   cout << i1 <<"  !=  "<< i2 << endl;

I want to decide, if the user has inputed a String or a zero, in order to perform further manipulation. Is there a clean way to decide this problem, without using lexical cast or atoi? best gegards

You could use an invalid default value:

#include<sstream>
#include<limits>
using std::numeric_limits;
int main(){
    std::string inputString = "TEXT 0"; 
    std::istringstream istr(inputString);
    int i1=numeric_limits<int>::min();
    int i2=numeric_limits<int>::min(); 
    std::string tmp;
    istr >> i1;
    if (i1 == numeric_limits<int>::min()) {
      // extraction failed
      i1 = 0;
      istr.clear(); // clear error flags to allow further extraction
      istr >> tmp; // consume the troublesome token
    }
    // same for i2
}

Note : The technique works if numeric_limits<int>::min() cannot be a valid input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM