views:

102

answers:

4

Hello there, This is related to my previous question. Basically, given a string of characters, how do I go through it and assign all the numbers within that string into an integer variable leaving out all other characters?

Not at input but when there is a string of characters already read in through gets();

A: 

Look up the strtol function from the standard C library. It allows you to find the part of a character array that is a number, and points to the first character that isn't a number and stopped the parsing.

Eli Bendersky
A: 

You can use sscanf: it works like scanf but on a string (char array).

sscanf might be overkill for what you want though, so you can also do this:

int getNum(char s[])
{
    int ret = 0;
    for ( int i = 0; s[i]; ++i )
        if ( s[i] >= '0' && s[i] <= '9' )
            ret = ret * 10 + (s[i] - '0');

    return ret;
}
IVlad
+3  A: 

This is a simple C++ way to do that:

#include <iostream>
#include <sstream>
using namespace std;   

int main(int argc, char* argv[]) {

    istringstream is("string with 123 embedded 10 12 13 ints", istringstream::in);
    int a;

    while (1) {
        is >> a;
        while ( !is.eof() && (is.bad() || is.fail()) ) {
            is.clear();
            is.ignore(1);
            is >> a;
        }
        if (is.eof()) {
            break;
        }
        cout << "Extracted int: " << a << endl;
    }

}
pajton
+4  A: 
unsigned int get_num(const char* s) {
  unsigned int value = 0;
  for (; *s; ++s) {
    if (isdigit(*s)) {
      value *= 10;
      value += (*s - '0');
   }
  }
  return value;
}

Edit: Here is a safer version of the function. It returns 0 if s is NULL or cannot be converted to a numeric value at all. It return UINT_MAX if the string represents a value larger than UINT_MAX.

#include <limits.h>

unsigned int safe_get_num(const char* s) {
  unsigned int limit = UINT_MAX / 10;
  unsigned int value = 0;
  if (!s) {
    return 0;
  }
  for (; *s; ++s) {
    if (value < limit) {
      if (isdigit(*s)) {
        value *= 10;
        value += (*s - '0');
      }
    }
    else {
      return UINT_MAX;
    }
  }
  return value;
}
Bertrand Marron
That is neat but...what if the value maxes out the maximum number for the type unsigned int?
tommieb75
I added a safer version.
Bertrand Marron