- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Converting Strings to Numbers in C/C++
In this tutorial, we will be discussing a program to understand how to convert strings into numbers in C/C++.
C/C++ provides two ways to convert strings into numbers.
Example
Using sscanf()
#include<stdio.h> int main(){ const char *str = "12345"; int x; sscanf(str, "%d", &x); printf("\nThe value of x : %d", x); return 0; }
Output
The value of x : 12345
Using stoi()
#include <iostream> #include <string> using namespace std; int main(){ string str1 = "45"; string str2 = "3.14159"; string str3 = "31337 geek"; int myint1 = stoi(str1); int myint2 = stoi(str2); int myint3 = stoi(str3); cout << "stoi(\"" << str1 << "\") is " << myint1 << '\n'; cout << "stoi(\"" << str2 << "\") is "<< myint2 << '\n'; cout << "stoi(\"" << str3 << "\") is "<< myint3 << '\n'; return 0; }
Output
stoi("45") is 45 stoi("3.14159") is 3 stoi("31337 geek") is 31337
Advertisements