简体   繁体   中英

How to get int from char in C

(i'm french, sorry for my bad english)

I don't know how to get an int from a char[], the patern of the char will be the same everytime : "prendre 2", "prendre 44", "prendre 710"...

I want to check if the pattern of the sentence is correct and get the integer.

I have try to do this, but as you see, the problem is i just can check if the integer is between 0-9 because I check only one char.

[...]

else if (est_prendre(commande)){
    /* if  the output is 1*/
    int number = commande[8]- '0'
}
int est_prendre(char *commande){
    int i;
    char temp[9] = "";
    char c = commande[8];
    int num = c - '0';
    for (i=0; i<8; i++){
        temp[i] = commande[i];
    }
    if (strcmp ("prendre ", temp) == 0)
    {
        if ( /*  num IS INTEGER?  */)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    } else {
        return 0;
    }

}

I expect if commande = "prendre 3", output of est_prendre is 1 because the pattern is correct And after than to put the integer into the variable number.

Thank You!

This is very basic, you should (re)read any reference/tutorial on C that you have used to learn the language.

You should just use the sscanf() standard function:

int value;
if (sscanf(commande, "prendre %d", &value) == 1)
{
  ... it was a match, the variable 'value' will be set to the number from the string
}

you can delete the (strange-looking) code that copies characters from commande to temp , and the temp variable too of course. Just inspect the commande string directly.

Assuming that 'commande + 8' is a valid substring, what you need is atoi() function (ASCII to Integer). This function is widely documented, and you can easily find online its usage.

int number = atoi(commande+8);

Just remember that the substring terminates at the first non-digit character:

  • atoi("23") returns 23
  • atoi("51hh37") returns 51
  • atoi("z3456") returns 0

Note: atoi converts input string into integer, and you can use it if you are sure it fits expected input. So, if you expect to have either long integers or float values in your string you can use atol() (ASCII to long) or atof() (ASCII to float).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM