How to read a binary number as input?

前端 未结 4 1871
爱一瞬间的悲伤
爱一瞬间的悲伤 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:27

    To take binary number as input, there are two ways I use frequently:

    (Key note: Take the input as string!!! use: #include)

    1. The to_ulong() method of the bitset template of the bitset library
      • for this you need to include the bitset library using #include

    Example :

    string s;
    cin>>s; // Suppose s = "100100101"
    int n = (int) bitset<64>(s).to_ulong();
    cout<

    Explore more about bitset here and about to_ulong() here.

    1. The stoi() method of the string library
      • for this you need to include the string library using #include

    Example :

    string s;
    cin>>s; // Suppose s = "100100101"
    int n = stoi(s, 0, 2);
    cout<

    Explore the format of stoi() here.

提交回复
热议问题