如何在 c 中将 ascii 码转换为字符
本文将演示关于如何在 c 中把 ascii 值转换为字符的多种方法。
在 c 中使用赋值运算符将 ascii 值转换为字符
ascii 编码支持 128 个唯一的字符,每个字符都被映射到相应的字符值。由于 c 语言编程语言在底层实现了 char
类型的数字,所以我们可以给字符变量分配相应的 int
值。举个例子,我们可以将 int
向量的值推送到 char
向量,然后使用 std::copy
算法将其打印出来到控制台,这样就可以按照预期的方式显示 ascii 字符。
请注意,只有当 int
值对应于 ascii 码时,分配到 char
类型才会有效,即在 0-127 范围内。
#include #include #include #include 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 值转换为字符的方法。在这个ag捕鱼王app官网的解决方案中,我们声明一个 char
数组来存储每次迭代的转换值,直到 printf
输出到控制台。sprintf
将字符数组作为第一个参数。接下来,你应该提供一个%c
格式指定符,它表示一个字符值,这个参数表示输入将被转换的类型。最后,作为第三个参数,你应该提供源变量,即 ascii 值。
#include #include #include #include #include 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 #include #include #include 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 浏览次数:315 分类:c
-
可以通过使用复位按钮,softwarereset 库和 adafruit sleepydog 库来复位 arduino。
发布时间:2024/03/13 浏览次数:181 分类:c
-
可以使用简单的方法 toint()函数和 serial.parseint()函数将 char 转换为 int。
发布时间:2024/03/13 浏览次数:151 分类:c
-
可以使用 arduino 中的循环制作计数器。