如何在 C++ 中將 ASCII 碼轉換為字元

Jinku Hu 2023年10月12日
  1. 在 C++ 中使用賦值運算子將 ASCII 值轉換為字元
  2. 使用 sprintf() 函式在 C++ 中把 ASCII 值轉換為字元
  3. 使用 char() 將 ASCII 值轉換為字元值
如何在 C++ 中將 ASCII 碼轉換為字元

本文將演示關於如何在 C++ 中把 ASCII 值轉換為字元的多種方法。

在 C++ 中使用賦值運算子將 ASCII 值轉換為字元

ASCII 編碼支援 128 個唯一的字元,每個字元都被對映到相應的字元值。由於 C 語言程式語言在底層實現了 char 型別的數字,所以我們可以給字元變數分配相應的 int 值。舉個例子,我們可以將 int 向量的值推送到 char 向量,然後使用 std::copy 演算法將其列印出來到控制檯,這樣就可以按照預期的方式顯示 ASCII 字元。

請注意,只有當 int 值對應於 ASCII 碼時,分配到 char 型別才會有效,即在 0-127 範圍內。

#include <charconv>
#include <iostream>
#include <iterator>
#include <vector>

using std::copy;
using std::cout;
using std::endl;
using std::vector;

int main() {
  vector<int> ascii_vals{97, 98, 99, 100, 101, 102, 103};
  vector<char> chars{};

  chars.reserve(ascii_vals.size());
  for (auto &n : ascii_vals) {
    chars.push_back(n);
  }
  copy(chars.begin(), chars.end(), std::ostream_iterator<char>(cout, "; "));

  return EXIT_SUCCESS;
}

輸出:

a; b; c; d; e; f; g;

使用 sprintf() 函式在 C++ 中把 ASCII 值轉換為字元

sprintf 函式是另一種將 ASCII 值轉換為字元的方法。在這個解決方案中,我們宣告一個 char 陣列來儲存每次迭代的轉換值,直到 printf 輸出到控制檯。sprintf 將字元陣列作為第一個引數。接下來,你應該提供一個%c 格式指定符,它表示一個字元值,這個參數列示輸入將被轉換的型別。最後,作為第三個引數,你應該提供源變數,即 ASCII 值。

#include <array>
#include <charconv>
#include <iostream>
#include <iterator>
#include <vector>

using std::array;
using std::copy;
using std::cout;
using std::endl;
using std::to_chars;
using std::vector;

int main() {
  vector<int> ascii_vals{97, 98, 99, 100, 101, 102, 103};

  array<char, 5> char_arr{};
  for (auto &n : ascii_vals) {
    sprintf(char_arr.data(), "%c", n);
    printf("%s; ", char_arr.data());
  }
  cout << endl;

  return EXIT_SUCCESS;
}

輸出:

a; b; c; d; e; f; g;

使用 char() 將 ASCII 值轉換為字元值

另外,可以使用 char() 將單個 ASCII 值強制轉換為 char 型別。下面的例子演示瞭如何從包含 ASCII 值的 int 向量直接向控制檯輸出字元。

#include <charconv>
#include <iostream>
#include <iterator>
#include <vector>

using std::copy;
using std::cout;
using std::endl;
using std::vector;

int main() {
  vector<int> ascii_vals{97, 98, 99, 100, 101, 102, 103};

  for (auto &n : ascii_vals) {
    cout << char(n) << endl;
  }

  return EXIT_SUCCESS;
}

輸出:

a
b
c
d
e
f
g
作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ Char