I'm somewhat new to C++, and I was wondering how to scanf into or printf out of a bitset, i.e., what is the appropriate type specifier for I/O to a bitset index? An example of what I would want to do is:
#include <bitset>
#include <stdio.h>
using namespace std;
int main()
{
bitset<1> aoeu;
scanf("%d" &bitset[0]); //this line
printf("%d" bitset[0]); // this line
}
As ChrisMM mentioned, you should use the the C++ way of doing input and output. Luckily, a std::bitset has overloads for operator<< and operator>> so you directly read from std::cin and write to std::cout, without needing to_string(), like so:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<1> aoeu;
std::cin >> aoeu; // read bitset from standard input
std::cout << aoeu; // write bitset to standard output
}
If you just want to read one specific bit and put it in a bitset, you have to do it a bit more indirect:
std::bitset<3> bits;
int value;
std::cin >> value; // read one integer, assuming it will be 0 or 1
bits[1] = value; // store it in the second bit of the bitset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With