2

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.

3
  • 1
    removed C tag as this has nothing to do with C
    – jk.
    Apr 3, 2011 at 7:11
  • My bad! I thought if there is some solution for this in C, then it also exists in C++ and hence put it there. Anyways, thanks for the edit Apr 3, 2011 at 7:14
  • 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). I don't believe that's a fair characterization of the performance of looping over the m strings of your vector, or of the performance of scanning the m * n characters of your collection of strings. In each case, it's still a linear scan of your input, and I don't think you can claim it's O(n^2) Apr 3, 2011 at 8:15

7 Answers 7

5

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;
}
8
  • Thanks for the reply. I edited my question, please let me know if there is an alternate solution. Thanks. Apr 3, 2011 at 7:01
  • @Shankar: why is this not a valid solution? atoi does almost the same, but with a bit more complex checks than just "is an integer" i think. Anyway it has to go through the string one character at a time so it will not perform better than this!
    – PeterK
    Apr 3, 2011 at 7:05
  • will fail for negative numbers
    – jk.
    Apr 3, 2011 at 7:06
  • @PeterK, I did not say this is an invalid solution. I wanted to know if there is a better solution to this. Apr 3, 2011 at 7:08
  • Thanks for the reply Peter. I will implement it this way because the istringstream does not distinguish between "123" and "123Shankar" Apr 3, 2011 at 7:35
3

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
}
1
  • This method does not work for the type "123Shankar". Please let me know if there is a way to detect this. Apr 3, 2011 at 7:20
3

Try using an istringstream

int value;
std::istringstream iss(yourvector[i]);
if(iss >> value)
   std::cout<<"value is not null"<<std::endl;
7
  • Thanks for the reply. Can you please explain a bit more on this? Because, I am getting an error: "Undefined structure 'istringstream' in function main()" Apr 3, 2011 at 7:10
  • @Shankar You need to include <sstream>, sorry I didn't specify that.
    – jonsca
    Apr 3, 2011 at 7:12
  • @Shankar I had tried it and I got: value is not null 123 What is your expected output for that case?
    – jonsca
    Apr 3, 2011 at 7:21
  • @jonsca: I am getting value is not null for both "123" and "123Shankar" Apr 3, 2011 at 7:25
  • 1
    @Shankar Take the length of the string and see if the tellg() method of the istringstream matches up with it. If there are still characters that weren't converted, then there's more than the number in there.
    – jonsca
    Apr 3, 2011 at 7:39
3
std::string intStr("123");
std::string nonintStr("hello");
try {
    int i = boost::lexical_cast<int>(intStr); //OK
    int j = boost::lexical_cast<int>("nonintStr); //throws
}
catch (boost::bad_lexical_cast & e) {
}
10
  • Thanks for the reply. Unfortunately I should not use any 3rd party library. I will have this edited in my question now. Apr 3, 2011 at 7:06
  • 1
    @Shankar: Why can you not use Boost? Technically, @Xeo's code has come from a third-party, so can you not use that either?
    – johnsyweb
    Apr 3, 2011 at 7:45
  • @Johnsyweb, I am not supposed to use a 3rd party library. Thats is what my professor insists on. Also, @Xeo's code doesn't use any third-party library IMHO Apr 3, 2011 at 7:49
  • 1
    @Shankar: He meant that I'm the "third-party". ;)
    – Xeo
    Apr 3, 2011 at 7:53
  • @Johnsyweb: LOL was that sarcasm? Nice! :) Apr 3, 2011 at 8:00
2

The nature of the problem requires scanning each character per string -- at least until a failure occurs. There is no way to magically take the whole string at-a-glance; any character that would cause it to not be a string would have to be discovered first.

If you find a general pattern with your non-strings -- maybe they are always of the form [numbers][letters] -- then you could have a shortcut check of the LAST character of the string first to exit early. For similar functions where performance matters, I test each corner-case first, and one in the direct middle, before iterating over everything.

Here's an example:

bool IsStringValidInt( const std::string& str )
{
    if( str.size() == 0 )
        return false;

    if( !isdigit( str[str.size() - 1] ) ||
        !isdigit( str[str.size() / 2] ) )
        return false;

    size_t i = 0;
    if( str[i] == '-' )
        ++i;

    for( ; i < str.size(); ++i )
        if( !isdigit( str[i] ) )
            return false;

    return true;
}
0
1

One way is to check each character of each string to see if it is a digit (usingisdigit)

1
  • Hi, thanks for the reply. But, is there any other better solution to this problem? Apr 3, 2011 at 6:57
1

The correct way to check with sscanf() is as follows:

int    val;
char   dummy;

if (sscanf(str, "%d%c", &val, &dummy) == 1) {
    ... // "val" contains the string's integer value
} else {
    ... // the string does not contain an integer
}

The important thing is that the %c component in the format string causes sscanf() to report if there is anything after the end of the bit that can be parsed as an integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.