Convert char to int in C and C++

前端 未结 12 1994
梦毁少年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:07

    Presumably you want this conversion for using functions from the C standard library.

    In that case, do (C++ syntax)

    typedef unsigned char UChar;
    
    char myCppFunc( char c )
    {
        return char( someCFunc( UChar( c ) ) );
    }
    

    The expression UChar( c ) converts to unsigned char in order to get rid of negative values, which, except for EOF, are not supported by the C functions.

    Then the result of that expression is used as actual argument for an int formal argument. Where you get automatic promotion to int. You can alternatively write that last step explicitly, like int( UChar( c ) ), but personally I find that too verbose.

    Cheers & hth.,

提交回复
热议问题