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.
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;
}