3

我对 C++ 有点陌生,我想知道如何从 bitset 中 scanf 或 printf,即,对于 bitset 索引的 I/O 合适的类型说明符是什么?我想做的一个例子是:

#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
}
4

2 回答 2

3

您关于如何完成此任务scanf的问题printf似乎是一个XY 问题。@GSliepen 提供的答案向您展示了如何在 C++ 中正确执行此操作。

但是,如果您真的对如何使用scanfand来完成此操作感兴趣printf(我不推荐),我会直接回答您的问题:

您不能scanf直接与位集一起使用,因为scanf至少需要一个字节的地址,而不是单个位。甚至不存在单个位的地址(至少在大多数平台上)。但是,您可以先使用scanf写入临时字节 ( unsigned char) 或 an int,然后将其转换为 bitset 的位,例如:

#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]) );
}

如果您想知道为什么我不是using namespace std;,尽管您在问题中这样做了,那么您可能想阅读这个 StackOverflow 问题

于 2020-07-24T23:55:38.480 回答
3

正如 ChrisMM 所提到的,您应该使用 C++ 方式进行输入和输出。幸运的是, astd::bitset有 for 的重载operator<<,因此您无需operator>>就可以直接读取std::cin和写入,如下所示:std::coutto_string()

#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
}

如果您只想读取一个特定位并将其放入位集中,则必须更间接地进行:

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
于 2020-07-24T23:01:45.217 回答