简体   繁体   中英

Convert a char to an int in C

I want to make a program which converts 3www2as3com0 to www.as.com but I have got trouble at the beginning; I want to convert the first number of the string (the character 3) to an integer to use functions like strncpy or strchr so when I print the int converted the program shows 51 instead of 3. What is the problem?

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

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

    /* argv[1]--->3www2as3com0*/

    char *string;
    char *p;  

    string=argv[1];
    p=string;

    char cond,cond2;

    cond=*p; //I want to have in cond the number 3

    cond2=(int)cond; //I want to convert cond (a char) to cond2(an int)

    printf("%d",cond2); //It print me 51 instead of 3

    return (EXIT_SUCCESS);
}

Your computer evidently encodes strings in a scheme called ASCII . (I am fairly sure most modern computers use ASCII or a superset such as UTF-8 for char* strings).

Notice how both printable and nonprintable characters are encoded as numbers. 51 is the number for the character '3'.

One of the nice features of ASCII is that all the digits have increasing codes starting from '0'.

This allows one to get the numerical value of a digit by calculating aDigitCharacter - '0' .

For example: cond2 = cond - '0';

EDIT:

You should also probably also double check that the character is indeed a digit by making sure it lies between '0' and '9' ;

If you want to convert a string containing more than one digit to a number you might want to use atoi . It can be found in <stdlib.h> .

The character's integer value is the ASCII code for the digit, not the number it actually represents. You can convert by subtracting '0' .

if( c >= '0' && c <= '9' ) val = c - '0';

Seems like the strings you are using will never have negative number, so you can use atoi(), returns the integer value from char. If it encounters something that is not a number, it will get the number that builds up until then.

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