簡體   English   中英

如何將用戶輸入(字符串)轉換為char數組?

[英]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;
}

此方法允許您接受任何長度的二進制表示。

編輯:添加注釋以解釋方法以及如何將二進制字符串轉換為整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM