如何将用户输入(字符串)转换为字符数组
How to convert user input (string) to char array?
我正试图编写一个程序,使用用户输入的二进制数将二进制转换为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';
}
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
int val = 0;
// Save the integer value of ascii 0s for convenience in converting
// input characters to integer representations.
static int ASCII_OFFSET_0 = static_cast<int>('0');
// Read input data from user.
string input;
cin >> input;
// now that we have some input, presumably all 0s and 1s,
// convert the characters of the strings to integers, and compute
// the total value in base 10 of the binary string represented by input.
// NB: It may be desirable to validate the input as only being '0' or '1'
// characters. But, other characters won't 'break' this.
for (int i=0; i < input.length(); i++)
{
// Current is the integer representation of character input[i]
// with the characters ascii offset removed. i.e '0' == (int)48
int current = static_cast<int>(input.at(i)) - ASCII_OFFSET_0;
// Utilize arithmetic shift operator to calculate the value associated
// with the position it falls at in input.
// NB: first character of input is considered highest order bit.
int shift_value = (input.length() - (i + 1));
// Bitwise or is used to continually update the true value we have read
// operates on the notion that 10 or 1 (binary) == 11 (binary)
val |= current << shift_value;
}
// Val now contains an integer representation of the string given to cin
cout << val << endl;
return 0;
}
这种方法允许您接受任何长度的二进制表示。
编辑:添加注释来解释该方法以及如何将二进制字符串转换为整数。
相关文章:
- HEX值到wchar_t字符(UTF-8)的转换
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 转换特殊字符(UTF-8)
- 将转换字符键入 int 以用作向量C++的索引
- 将字符随机转换为大写的函数
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 转换字符时Arduino DUE 和 Arduino UNO 之间的区别
- 如何在C++中正确重载运算符转换字符*?
- 如何转换数据结构以在 c++ 中转换字符*
- 不兼容的转换字符
- 将转换字符数组[16]键入为int 128位
- 在c++中转换字符编码
- 使用递归转换字符
- 如何在Objective-C/C/C++中转换字符和字节的位置
- C++到Pep/8汇编语言的转换——字符数组
- 转换字符>十六进制