Check if string ends with (%i) then assign that number in a variable

112 views Asked by At

Lets say I have a string "MyName(10)"
I want to check a string ending with (%i) and assign that number in a variable.
I tried sscanf but its not working.

sscanf("MyName(10), "%s(%i)", tempName, &count);

Its storing MyName(10) in tempName and count is 0.

MyName can be variable length , its not fixed as "MyName" it can be "Mynaaaaaame".

3

There are 3 answers

0
CPPLearner On
sscanf(Name, "%*[^(]%c%i%[^)]%*c", &var);
1
theadnangondal On

try this sample code.. may be this can help ... You can adjust anything according to your needs

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define IS_DIGIT(x) \
    ( x == '0' || x == '1' || x == '2' || \
      x == '3' || x == '4' || x == '5' || x == '6' || \
      x == '7' || x == '8' || x == '9' )


/* the function will return 0 in success and -1 in error */
/* on success num will contain the pointer to the number */

int 
check_last_num(char * str , int * num)
{
    int len = strlen(str);
    int index = len - 1;

    /* make sure the last char is ')' */
    if (str[index] != ')')
    return -1;

    while ( --index  >= 0 && (str[index] != '(') ) {
    char c = str[index];
    if ( ! IS_DIGIT(c) )
        return -1;  
    }

    /* loop exit check */
    if (index < 0)
    return -1;

    *num = atoi((const char *) &str[index + 1]);

    return 0;
}

int main(int argc , char *argv[] )
{
    int rc ; 
    if ( 0 == check_last_num("MyName(890790)" , & rc))
    printf ("%d \n" , rc);
    else 
    printf ("error \n");

    return 0;
}
0
NathanOliver On

Since this is tagged as C++ you can do it like:

void assignVariable(std::string& s, std::string replace, int value)
{
    std::size_t pos;
    while ((pos = s.find(replace)) != std::string::npos)
        s.replace(pos, 2, std::to_string(value));
}

int main()
{
    std::string name = "%imyname(%i)%i";
    assignVariable(name, "%i", 365);
    std::cout << name;
    cin.get();
    return 0;
}

This will replace all occurrences of replace in the string passed to the function. If you wanted to limit it to only that last occurrence then you can use std::string::find_last_of()