Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanf/printf to input into/output from a bitset

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
}
like image 400
skang Avatar asked Oct 28 '25 02:10

skang


1 Answers

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
like image 92
G. Sliepen Avatar answered Oct 29 '25 16:10

G. Sliepen