
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How do I convert a char to an int in C and C++?
In C language, there are three methods to convert a char type variable to an int. These are given as follows −
- sscanf()
- atoi()
- Typecasting
Here is an example of converting char to int in C language,
Example
#include<stdio.h> #include<stdlib.h> int main() { const char *str = "12345"; char c = 's'; int x, y, z; sscanf(str, "%d", &x); // Using sscanf printf("\nThe value of x : %d", x); y = atoi(str); // Using atoi() printf("\nThe value of y : %d", y); z = (int)(c); // Using typecasting printf("\nThe value of z : %d", z); return 0; }
Output
Here is the output:
The value of x : 12345 The value of y : 12345 The value of z : 115
In C++ language, there are two following methods to convert a char type variable into an int −
- stoi()
- Typecasting
Here is an example of converting char to int in C++ language,
Example
#include <iostream> #include <string> using namespace std; int main() { char s1[] = "45"; char c = 's'; int x = stoi(s1); cout << "The value of x : " << x; int y = (int)(c); cout << "\nThe value of y : " << y; return 0; }
Output
Here is the output
The value of x : 45 The value of y : 115
- Related Articles
- How to convert a single char into an int in C++
- How to convert an std::string to const char* or char* in C++?
- Swift Program to Convert Char type variables to Int
- Haskell Program to convert int type variables to char
- How to convert an int to string in C++?
- How to convert a std::string to const char* or char* in C++?
- How do I reverse an int array in Java
- What should I do? Select int as currency or convert int to currency format in MySql?
- Convert an int to ASCII character in C/C++
- How to convert a String to an int in Java
- Golang Program to Convert Char Type Variables to Int Using Inbuilt Functions
- How to convert a Java String to an Int?
- How to convert string to char array in C++?
- How to convert a string into int in C#?
- How to assign int value to char variable in Java

Advertisements