简体   繁体   中英

Converting char to int in C

I have searched for this for quite some time before posting this question. The answer to it should be fairly easy though, since I am an ultra-beginner atm.

I have a char* in which I want a user to put some digits (over 20), that in turn can be called upon specifically.

This is what I've tried:

    char* digits = GetString();
    int prime = digits[0];

When I verify whether this worked with printf I find prime to have become 0.

    printf("prime:%d\ndigits:%c\n",prime, digits[0]);

Why would this be and what could I do to make this work?

Edit: Is it perhaps easier to make an int array and use GetLongLong?

Neither C or C++ guarantees what value will be used to encode the character 0 , but both guarantee that digits will be contiguous and ordered, so (for example) digits[0]-48 may or may not work, but digits[0] - '0' is guaranteed to work (presuming that digits[0] actually holds a digit, of course).

The precise requirement in the C++ standard (§2.3/3) is:

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

At least as of C99, the C standard has identical wording, but at §5.2.1/3.

The character zero ('0') has the numeric value of 48, '1' is 49, and so on.

You may find this a useful idiom to get the numeric value from the ascii value.

int prime = digits[0] - '0';

You may also find looking at man ascii informative (or similar man page if you use some other charset) .

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