-2

I'm trying to calculate the value a string in C.

I define the string like: char cadena[100] = "Esto es un text securizado$2516"

I need to transform 2516 into an int, I'm actually trying to use atoi(), but I don't know how to separate the string to use the function.

PS: Excuse my English, it's not my native language, I hope you understand what I want to do.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
Eusebio
  • 1
  • 1
  • `value=atoi(strchr(cadena,'$')+1);` But this is simplistic, will fall over horribly if there is no `'$'` – Weather Vane Nov 19 '15 at 20:31
  • 2
    Use `strcspn()` to skip over the non-number characters, then use `atoi` on the rest. – Barmar Nov 19 '15 at 20:31
  • You may use `strchr()` to obtain a pointer to the first occurrence of a character in your string. You may use that to find where the "$" is. – init_js Nov 19 '15 at 20:36
  • Possibly duplicate of http://stackoverflow.com/questions/13399594/how-to-extract-numbers-from-string-in-c – Ashraful Islam Nov 19 '15 at 20:37
  • Or even use `strrchr(cadena, '$')`, which finds the first occurrence of a dollar sign from the end in case the string proper has dollars and/or numbers. – M Oehm Nov 19 '15 at 20:37
  • 2
    You need to define the rule before you can implement it. It's impossible for us to tell the rule from just one example. For example, I can think of three possible answers if the string is "Esto es 2516 en $2500 or 1400", depending on exactly what the rule is. (Is the rule to use the first number? The last number? The one preceded by a `$`? Or what?) – David Schwartz Nov 19 '15 at 20:40

3 Answers3

1

A straightforward approach can look the following way

int number = 0;
char cadena[100] = "Esto es un text securizado$2516";

size_t n = strcspn( cadena, "0123456789" );

if ( cadena[n] ) number = atoi( cadena + n );

Or if the number is already initialized by 0 then you can just write

number = atoi( cadena + n );

In this case zero will be a default value.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can use strrchr to find the rightmost occurrence of a character. It returns a pointer to that rightmost character, or NULL if it was not found:

char *p;
int n;
if ((p = strrchr(cadena, '$')) != NULL)
    sscanf(p + 1, "%d", &n);

Notice we add 1 to p. This is because p points to the $ character.

And don't use atoi, since it does no error checking. On the other hand, sscanf returns 0 on failure.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
0
#include <stdio.h>

int main(void){
    char cadena[100] = "Esto es un text securizado$2516";
    int value = 0;
    size_t i;

    for(i = 0; cadena[i]; ++i){
        if(1 == sscanf(cadena + i, "%d", &value))//try and get
            break;
    }
    printf("%d\n", value);

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70