如何在C++中将整数转换为字符
How to convert an integer to a character in C++
假设我有一个整数,我想将它转换为一个字符?在 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++
}
可以用数组,应该很容易理解:
if (i >= 0 && i <= 9) {
char digits[] = "0123456789";
char c = digits[i];
或者你可以使用加法,这有点难以理解。它依赖于(保证的)细节,即字符编码中的数字符号是连续的:
if (i >= 0 && i <= 9) {
char c = i + '0';
char c = digit + '0' ;
它会完成你的工作。
一个安全的方法是使用 std::stoi(), https://en.cppreference.com/w/cpp/string/basic_string/stol
您拥有使用安全字符串类型 (std::string) 的所有好处,
当您输入错误时,stoi 将抛出异常。
#include <string>
int main()
{
std::string txt("123");
auto value = std::stoi(txt);
}
也尽量不要使用#include
.
假设我有一个整数,我想将它转换为一个字符?在 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++
}
可以用数组,应该很容易理解:
if (i >= 0 && i <= 9) {
char digits[] = "0123456789";
char c = digits[i];
或者你可以使用加法,这有点难以理解。它依赖于(保证的)细节,即字符编码中的数字符号是连续的:
if (i >= 0 && i <= 9) {
char c = i + '0';
char c = digit + '0' ;
它会完成你的工作。
一个安全的方法是使用 std::stoi(), https://en.cppreference.com/w/cpp/string/basic_string/stol
您拥有使用安全字符串类型 (std::string) 的所有好处, 当您输入错误时,stoi 将抛出异常。
#include <string>
int main()
{
std::string txt("123");
auto value = std::stoi(txt);
}
也尽量不要使用#include