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

时间:2014-11-06 13:28:57

标签: c++ arrays string

我试图编写一个程序,使用用户输入的二进制数将二进制转换为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循环来传递单个字符串,而不是这个,用户输入一个整数数组,然后可以在计算中使用。 我该怎么做?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

此方法允许您接受任何长度的二进制表示。

编辑:添加注释以解释该方法以及如何将二进制字符串转换为整数。