简体   繁体   中英

How to accept binary input from user in C++?

I want to do a binary operation in C++, namely XOR, on a binary input given by the user. The user will enter a sequence of zeros and ones only. How can I declare a variable to accept the input 1's and 0's as binary bits?

A convenient way is to use std::bitset . If you have a look at its constructors , there are options to construct a bit set from several data sources including std::string and C-style strings. Constructors validate the input and throw an exception in case invalid input is given.

You can then use its bitwise operators directly. XOR is operator^ .

std::bitset is a fixed-size container, so you'll have to specify the maximum expected length as a constexpr value.

get the sequence as a string, then use strtol with base 2 | or create your own function to convert the string into a integer (that's not really difficult) | or use the string directly (string[i]-'0')^...

Open your mind ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM