Cameron Cassidy
Cameron Cassidy

Reputation: 73

extracting an int from a string using isdigit

I'm needing to parse a string and convert the first series of digits into an integer.

Here is the function:

    int get_int (string to) {
    string temp = "";
    for ( int i = 0 ; i < to.length(); i++) {
        if (isdigit((unsigned char)to[i])) {
            cerr << to[i];
            temp = temp+to[i]; 
        }
        i++; 
    }
    return stoi(temp); 
}

and I'm passing it: "test: 19764\n". However, I'm getting the output 174 (both in print and return value). What is going on?

Thanks, Cameron

Upvotes: 0

Views: 61

Answers (1)

Marco A.
Marco A.

Reputation: 43662

The problem is: extra condition increment

int get_int (string to) {
  string temp = "";
  for ( int i = 0 ; i < to.length(); i++) { <--
    if (isdigit((unsigned char)to[i])) {
        cerr << to[i];
        temp = temp+to[i]; 
    }
    i++; <--
  }
return stoi(temp); 
}

If I really had to do this using isdigit I would rather go with something along the lines of

int get_int(string to) { // Assumes a base10 representation
  int value = 0;
  for (int i = 0; i < to.length(); ++i) {
    if (isdigit(to[i])) {
      cerr << to[i];
      value = value * 10 + (to[i] - 0x30);
    }
  }
  return value;
}

Not sure why you need to output the digits to cerr though.

Upvotes: 1

Related Questions