How to read a binary number as input?

前端 未结 4 1876
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 12:35

Is there a way for the user to input a binary number in C or C++?

If we write something like

int a = 0b1010;
std::cout << a << std::endl
         


        
4条回答
  •  轮回少年
    2021-02-03 13:10

    While there is no function to read binary numbers directly, there are functions, strtox (where x represents the data type) to convert a string containing a binary number (or a number of any other base) to a numeric value.

    So the solution is to first read the number as a string and then convert it.

    Example:

    char input[100];
    char *endpointer;
    
    
    
    int n = (int) strtol(input, &endpointer, 2);
    

提交回复
热议问题