
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Char to 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 ?
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
Advertisements