迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > C++ >

如何在 C++ 中将 ASCII 码转换为字符

作者:迹忆客 最近更新:2024/01/02 浏览次数:

本文将演示关于如何在 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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Arduino 中停止循环

发布时间:2024/03/13 浏览次数:444 分类:C++

可以使用 exit(0),无限循环和 Sleep_n0m1 库在 Arduino 中停止循环。

Arduino 复位

发布时间:2024/03/13 浏览次数:315 分类:C++

可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。

Arduino 的字符转换为整型

发布时间:2024/03/13 浏览次数:181 分类:C++

可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。

Arduino 串口打印多个变量

发布时间:2024/03/13 浏览次数:381 分类:C++

可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。

Arduino if 语句

发布时间:2024/03/13 浏览次数:123 分类:C++

可以使用 if 语句检查 Arduino 中的不同条件。

Arduino ICSP

发布时间:2024/03/13 浏览次数:214 分类:C++

ICSP 引脚用于两个 Arduino 之间的通信以及对 Arduino 引导加载程序进行编程。

使用 C++ 编程 Arduino

发布时间:2024/03/13 浏览次数:127 分类:C++

本教程将讨论使用 Arduino IDE 在 C++ 中对 Arduino 进行编程。

Arduino 中的子程序

发布时间:2024/03/13 浏览次数:168 分类:C++

可以通过在 Arduino 中声明函数来处理子程序。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便