skang
skang

Reputation: 41

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
}

Upvotes: 4

Views: 3037

Answers (3)

Tahuti
Tahuti

Reputation: 31

To print the value of a specific bit j printf("%d", aoeu(j));

To print the value of the whole bitset I would suggest using

printf("%s\n", val.to_string().c_str());

Upvotes: 0

Andreas Wenzel
Andreas Wenzel

Reputation: 25261

Your question on how to accomplish this with scanf and printf seems to be an XY problem. The answer provided by @GSliepen shows you how to do it properly in C++.

However, in case you are really interested on how to accomplish this using scanf and printf (which I don't recommend), I will give you a direct answer to your question:

You cannot use scanf directly with bitsets, because scanf requires an address to at least a byte, not a single bit. Addresses to single bits don't even exist (at least on most platforms). However, you can first use scanf to write to a temporary byte (unsigned char) or an int and then convert it to a bit for the bitset, for example like this:

#include <bitset>
#include <cstdio>
#include <cassert>

int main() 
{
    std::bitset<1> aoeu;
    int ret, input;

    ret = std::scanf( "%d", &input );
    assert( ret == 1 );

    aoeu[0] = input;

    std::printf( "%d\n", static_cast<int>(aoeu[0]) );
}

In case you are wondering why I am not using namespace std;, although you do in your question, then you may want to read this StackOverflow question.

Upvotes: 3

G. Sliepen
G. Sliepen

Reputation: 7983

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

Upvotes: 3

Related Questions