【发布时间】:2021-10-22 18:59:42
【问题描述】:
假设我有一个整数,我想将它转换为一个字符?在 C++ 中可以使用或应该使用哪些方法?例如,参考下面给出的代码
#include <bits/stdc++.h>
using namespace std;
int main
{
int i = 1;
// Say I want to convert 1 to a char '1';
// How do I achieve the following in C++
}
【问题讨论】:
-
只要
1 + '0'。 -
char c = '0' + i; -
为什么是
rcpp标签?和never include<bits/stdc++.h>。此外,对于简单的示例,它可能是橡木味的,但否则using namespace std;是a bad habit。 -
至于您的问题,C++ 规范规定所有数字必须连续编码。也就是说,
'2'必须恰好比'1'大一,而'1'又必须比'0'大一。由此可以推断,普通算术(加法和减法)可用于从一个数字到其对应的字符,或相反。 -
顺便说一下,数字的“连续”只为数字指定。它不能可靠地或便携地用于其他任何事情。
标签: c++ type-conversion char integer