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?
-
Read as string, and then verify the input.Some programmer dude– Some programmer dude2014-03-26 19:54:10 +00:00Commented Mar 26, 2014 at 19:54
-
I am actually a beginner in C++ and programming too. How can I verify the input? And for what purpose?Mohamed Ahmed– Mohamed Ahmed2014-03-26 19:55:34 +00:00Commented Mar 26, 2014 at 19:55
Add a comment
|
2 Answers
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.
3 Comments
Mohamed Ahmed
I am not sure if bitset enables me to have the user specify the length of the input sequence?!
Mohamed Ahmed
Will constexpr enable variable size sequence? The program I want to have asks the user to enter the length of the sequence before entering the sequence itself.
iavr
@MohamedAhmed As I said, the size is fixed, that is, known at compile time. This can be just a maximum, e.g. 256 bits. The user just enters the string representation that should not be longer than that.