Convert char to int in C and C++

前端 未结 12 2129
梦毁少年i
梦毁少年i 2020-11-22 02:41

How do I convert a char to an int in C and C++?

12条回答
  •  余生分开走
    2020-11-22 03:15

    Well, in ASCII code, the numbers (digits) start from 48. All you need to do is:

    int x = (int)character - 48;
    

    Or, since the character '0' has the ASCII code of 48, you can just write:

    int x = character - '0';  // The (int) cast is not necessary.
    

提交回复
热议问题