Converting int to char in C

后端 未结 7 524
不知归路
不知归路 2021-01-18 03:55

Right now I am trying to convert an int to a char in C programming. After doing research, I found that I should be able to do it like this:

int value = 10;
c         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 04:11

    1. Converting int to char by type casting

    Source File charConvertByCasting.c

    #include 
    
    int main(){
        int i = 66;              // ~~Type Casting Syntax~~
        printf("%c", (char) i); //  (type_name) expression
        return 0;
    }
    

    Executable charConvertByCasting.exe command line output:

    C:\Users\boqsc\Desktop\tcc>tcc -run charconvert.c
    B
    

    Additional resources:
    https://www.tutorialspoint.com/cprogramming/c_type_casting.htm https://www.tutorialspoint.com/cprogramming/c_data_types.htm

    2. Convert int to char by assignment

    Source File charConvertByAssignment.c

    #include 
    
    int main(){
        int i = 66;
        char c = i;
        printf("%c", c);
        return 0;
    }
    

    Executable charConvertByAssignment.exe command line output:

    C:\Users\boqsc\Desktop\tcc>tcc -run charconvert.c
    B
    

提交回复
热议问题