Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with string to int conversion in C++

I have an application where I get a vector<string>. I need to iterate through each element in the vector and see if a value is an integer value.

Although the vector represents strings, few of the elements can contain an integer. I need to figure out which of those elements are integers, and if an element is an integer, I need its value. If an element in the vector is a string, then I just ignore it.

I tried to use atoi(vector[index].c_str()), but I have an issue with it. atoi returns an integer value if the value contained in the string is an integer. If not, it returns 0

So, consider the following:

atoi("Shankar") = 0
atoi("0") = 0

and

atoi("123") = 123
atoi("123Shankar") = 123

So, how do I distinguish between the above shown cases? If this cannot be achieved using atoi, then what is the alternate solution to this problem?

Please assist.

EDIT:

I can loop through the string and see if every character is an integer, but that reduces performance, since for m strings with an average of n characters, I need to check m X n times which makes it O(n^2).

is there a better way to solve this problem?

EDIT2:

Unfortunately, I cannot use any 3rd party library for this and just use STL

EDIT3:

In my application, the vector does not contain any negative integers so I am considering Xeo's solution since sstream does not distinguish between "123" and "123Shankar"

Thanks everyone for your assistance.

like image 748
Shankar Raju Avatar asked Aug 24 '26 20:08

Shankar Raju


2 Answers

Just go through your string and check every character if it's an integer. If not, break out and report false.

bool IsDigit(char c){
  return '0' <= c && c <= '9';
}

bool IsInteger(std::string const& str){
  size_t i = 0;
  if(*str == '-') ++i;
  for( ; i < str.size(); ++i){
     if(!IsDigit(str[i]))
       return false;
  }
  // all chars are integers
  return true;
}

Edit
atoi doesn't really do anything else. See this example implementation:

int StrToInt(char const* str){
  int ret = 0, sign = 1;
  if(*str == '-'){
    sign = -1;
    ++str;
  }
  while(IsDigit(*str)){
    ret *= 10; // make room for the next digit
    ret += ((*str) - 0x30); // convert char to digit
    ++str;
  }
  return ret * sign;
}
like image 63
Xeo Avatar answered Aug 27 '26 17:08

Xeo


You can use sscanf:

if(sscanf(s, "%d", &i) == EOF){
    // error
}

or with c++:

string s = "111";
stringstream ss(s);
int i;  
if((s >> i).fail()){
     //error
}
like image 41
GWW Avatar answered Aug 27 '26 16:08

GWW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!