Как перевести int в char c
In this article, we will learn how to convert int to char in C++. For this conversion, there are 5 ways as follows:
- Using typecasting.
- Using static_cast.
- Using sprintf().
- Using to_string() and c_str().
- Using stringstream.
Let’s start by discussing each of these methods in detail.
Examples:
Input: N = 65
Output: A
Input: N = 97
Output: a
1. Using Typecasting
Method 1:
- Declaration and initialization: To begin, we will declare and initialize our integer with the value to be converted.
- Typecasting: It is a technique for transforming one data type into another. We are typecasting integer N and saving its value in the data type char variable c.
- Print the character: Finally, print the character using cout.
Below is the C++ program to convert int to char using typecasting:
Method 2:
- Declaration and initialization: To begin, we will declare and initialize our integer with the value to be converted.
- Typecasting: Declare another variable as character c and assign the value of N to the C
- Print the character: Finally, print the character using cout.
Below is the C++ program to convert int to char using typecasting:
2. Using static_cast
The integer can be converted to a character using the static_cast function. Below is the C++ program to convert int to char using static_cast:
3. Using sprintf()
Allot space for a single int variable that will be converted into a char buffer. It is worth noting that the following example defines the maximum length Max_Digits for integer data. Because the sprintf function sends a char string terminating with 0 bytes to the destination, we add sizeof(char) to get the char buffer length. As a result, we must ensure that enough space is set aside for this buffer.
Below is the C++ program to convert int to char using sprintf():
4. Using to_string() and c_str()
The to string() function transforms a single integer variable or other data types into a string. The c_str() method converts a string to an array of characters, terminating with a null character.
Below is the C++ program to convert int to char using to_string() and c_str():
5. Using stringstream
A stringstream connects a string object to a stream, allowing you to read from it as if it were a stream (like cin). Stringstream requires the inclusion of the sstream header file. The stringstream class comes in handy when processing input.
Convert Integer to Char in C
This tutorial introduces how to convert an integer value into a character value in C. Each character has an ASCII code, so it’s already a number in C. If you want to convert an integer to a character, simply add ‘0’ .
Add ‘0’ to Convert an int to char
The ‘0’ has an ASCII value of 48. so, we have to add its value to the integer value to convert it into the desired character. The program is as below:
Below is a program that will convert an integer to the character only between 0 to 9.
Another program to convert an integer value to a character is as below:
Assign an int Value to char Value
Another way to convert an integer value to a character value is to assign an integer value to a character value as below: The character value corresponding to an integer value is printed here.
Below is another way to convert an integer value to a character value. Here, the value is typecasted, so the value 67 gets converted into the corresponding ASCII value.
sprintf() Function to Convert an Int to a Char
The sprintf() function works the same as the printf() function but instead of sending output to console, it returns the formatted string.
The first argument to the sprintf() function is a pointer to the target string. The remaining arguments are the same as for the printf() function.
Syntax of sprintf()
- strValue is a pointer to the char data type.
- format is used to display the type of output along with the placeholder.
- [arg1,arg2. ] are the integer(s) to be converted.
The function writes the data in the string pointed to by strValue and returns the number of characters written to strValue , excluding the null character. The return value is generally discarded. If any error occurs during the operation, it returns -1 . The program to convert an integer to a character is as below:
Преобразовать int в char в C#
В этом посте будет обсуждаться, как преобразовать int в char в C#.
1. Явное преобразование (приведения)
C# не поддерживает неявное преобразование типа "int" в "char", поскольку это преобразование небезопасно для типов и может привести к потенциальной потере данных. Однако мы можем сделать явное преобразование с помощью оператора приведения () . Приведение информирует компилятор о том, что преобразование является преднамеренным.
Следующая программа преобразует значение целого числа в значение типа Char.
Преобразование значения типа int в char
Составьте программу, которая напечатает рисунок, используя символы из таблицы ASCII (см. Рисунок 1).
Преобразовать код символа в символ типа char можно, методом преобразования целого значения в символьное.
Используя оператор вывода cout и подобрав нужный символ, можно достичь такого же результата, как на рисунке 1.

Рисунок 1 — Таблица ASCII
Программа написана под виндовс, так как все операции с символами выполняются с использованием кодировки ASCII, которая внедрена только в ОС Windows.