gpt4 book ai didi

c++ - 如何将用户输入(字符串)转换为字符数组?

转载 作者:行者123 更新时间:2023-11-30 02:42:47 28 4
gpt4 key购买 nike

我正在尝试编写一个程序,使用用户输入的二进制数将二进制转换为 base10

这是原始的“低效”代码:

void BASE10() {
int col_0, col_1, col_2, col_3, col_4, col_5, col_6, col_7;
cout << "Please enter the Binary number you would like to convert ONE digit at a time" << endl;
cin >> col_0;
cin >> col_1;
cin >> col_2;
cin >> col_3;
cin >> col_4;
cin >> col_5;
cin >> col_6;
cin >> col_7;
int num = 0;

if (col_0 == 1) {
num = num +128;
}
if (col_1 == 1) {
num = num +64;
}
if (col_2 == 1) {
num = num +32;
}
if (col_3 == 1) {
num = num +16;
}
if (col_4 == 1) {
num = num +8;
}
if (col_5 == 1) {
num = num +4;
}
if (col_6 == 1) {
num = num +2;
}
if (col_7 == 1) {
num = num +1;
}

cout << num << endl;

Restart();

我想使用 for 循环来传递单个字符串,而不是这个,用户输入到一个整数数组中,然后可以在计算中使用该数组。我该怎么做?

最佳答案

#include <iostream>
#include <string>
#include <bitset>

int main()
{
const std::string str = "00100101";
std::cout << std::bitset<8>(str).to_ulong() << '\n';
}

关于c++ - 如何将用户输入(字符串)转换为字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26780733/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com