Home > Mobile >  Problem assigning integer a value from an array index
Problem assigning integer a value from an array index

Time:08-12

I am trying to create a function that takes a string as an input and extracts the first digit as an output. Here is the relevant code. I am new to coding so tips are appreciated.

int extractNum(string id){
    int num=0;
    bool found=false;

    for(int i=0; i<id.length(); i  ){
        if(isdigit(id[i])){
            num=id[i];
            found=true;
            if(found=true){
                break;
            }
        }  
    }
    return num;
};

The problem I am facing is when ever I pass a example string like "vr2498" it does take the '2' but on assigning the value to a variable or returning the value it changes to 50. Which is incorrect.

Summary: Need to extract first digit from a string.

CodePudding user response:

Your restult num is an integer, but the "2" in your string is a character. When you assign num=id[i], you're converting the character "2" to its ASCII value, which is 50.

So, you need to convert that. The simplest way would be to just do num = id[i] - '0'. That works because in ASCII, numbers are consecutive with "0" being the first one.

The better solution here would be to use something like std::stoi which does that conversion. This would also allow converting more than one digit if that's what you want.

Also note you can just return from the loop directly, no need for break and found.

int extractNum(string id){
   for(int i=0; i<id.length(); i  ){
        if(isdigit(id[i])){
            //here, you could take more than one character
            const auto digitString = id.substr(i, 1);
            return std::stoi(digitString);               
        }  
    }
    return 0;
};

CodePudding user response:

int extractNum(string id){
    int num=0;
    bool found=false;

    for(int i=0; i<id.length(); i  ){
        if(isdigit(id[i])){
            num=id[i];
            found=true;
            if(found=true){
                break;
            }
        }  
    }
    return num-'0';
}

The value you are getting is the ASCII value of 2 as '2' is still a character for the compiler and is integral value is 50 Just subtract the required character with character '0' to get the actual integral value

CodePudding user response:

Check the ASCII value of '2', it is 50.
You can subtract '0', to get a value 2.
This is assuming you want some hands-on.
There are functions to do this for you.

  • Related