Skip to content
Related Articles

Related Articles

Converting Strings to Numbers in C/C++

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 22 May, 2022

Converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. But lack of knowledge of certain essential tools binds us to do so. Some methods to achieve this task are mentioned in this article.

For Number to String Conversion refer to the article Converting Numbers to String in C++

Converting Strings to Numbers

There are 3 major methods to convert a number to a string, which are as follows:

  • Using string Stream 
  • Using stoi()
  • Using atoi()
     

1. Using stringstream class or sscanf()

stringstream(): This is an easy way to convert strings of digits into ints, floats, or doubles. A number stream declares a stream object which first inserts a string, as a number into an object, and then uses ‘stringstream()’ to follow the internal conversion.

Example:

CPP




// C++ program to demonstrate the 
// use of a stringstream to
// convert string to int
#include <iostream>
#include <sstream>
using namespace std;
  
int main()
{
    string s = "12345";
  
    // object from the class stringstream
    stringstream geek(s);
  
    // The object has the value 12345 and stream
    // it to the integer x
    int x = 0;
    geek >> x;
  
    // Now the variable x holds the value 12345
    cout << "Value of x : " << x;
  
    return 0;
}

Output:

Value of x : 12345
// A stringstream is similar to input/output
// file stream. We need to declare a stringstream
// just like an fstream, for example: 
stringstream ss;

// and, like an fstream or cout, 
// we can write to it:
ss << myString; or 
ss << myCstring; or
ss << myInt;, or float, or double, etc.

// and we can read from it:
ss >> myChar; or
ss >> myCstring; or
ss >> myInt;  

To summarize, stringstream is a convenient way to manipulate strings. ‘sscanf() is a C style function similar to scanf(). It reads input from a string rather than standard input. 

Syntax of sscanf:

int sscanf ( const char * s, const char * format, ...);

Return type: Integer

Parameters:

  • s – string used to retrieve data
  • format – a string that contains the type specifier(s)…
  • : – arguments contain pointers to allocate storage with the appropriate type.

There should be at least as many of these arguments as the number of values stored by the format specifiers.

On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.

CPP




// C++ program to demonstrate 
// the working of SSCANF() to
// convert a string into a number
#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:

Value of x : 12345

Similarly, we can read float and double using %f and %lf respectively.

C++




// C++ program to show how SSCANF() 
// can work with floating numbers
#include <stdio.h>
int main()
{
    const char* str = "12345.54";
    float x;
    sscanf(str, "%f", &x);
    printf("\nThe value of x : %f", x);
    return 0;
}

C++




// C++ program to show how SSCANF() 
// can work with double numbers
#include <stdio.h>
int main()
{
    const char* str = "12345.54";
    double x;
    sscanf(str, "%lf", &x);
    printf("\nThe value of x : %lf", x);
    return 0;
}

Output 1:

The value of x : 12345.540039 // output of floating number

Output 2:

The value of x : 12345.540000 // output of double number

If the values are the same then why the outputs are different?

The reason behind this is that Floating numbers are all about speed, precision, and convenience in addition to which they use a binary representation to display their output which somewhat brings the output to the closest approximation; that’s why there are those extra digits at the end of the output. In addition to that in double numbers, the value will be shown as it is because double is all about accuracy and reliability, though it consumes more space than float and is also a bit slower than floating numbers. 

2. String Conversion Using stoi()

stoi(): The stoi() function takes a string as an argument and returns its value in integer form. And if you observe stoi() a little closer you will find out that it stands for:

   s    to     i()

|  |   |___> integer
|  |_______> to
|__________> String 

Example:

CPP




// C++ program to demonstrate working of stoi()
// Work only if compiler supports C++11 or above
// Becasue STOI() was added in C++ after 2011
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    string str1 = "45";
    string str2 = "3.14159";
    string str3 = "31337 geek";
  
    int myint1 = stoi(str1); // type of explicit type casting
    int myint2 = stoi(str2); // type of explicit type casting
    int myint3 = stoi(str3); // type of explicit type casting
  
    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 

3. String Conversion Using atoi()

The atoi() function takes a character array or string literal as an argument and returns its value in an integer form. And if you observe atoi() a little closer you will find out that it stands for:

a   to   i
|   |    |____> integer 
|   |_________> to
|_____________> Argument    

Example:

CPP




// C++ program to demonstrate the functioning of 
// the ATOI() function
#include <cstdlib>
#include <iostream>
using namespace std;
  
int main()
{
    const char* str1 = "42";
    const char* str2 = "3.14159";
    const char* str3 = "31337 geek";
  
    int num1 = atoi(str1); // explicit type casting
    int num2 = atoi(str2); // explicit type casting
    int num3 = atoi(str3); // explicit type casting
  
    cout << "atoi(\"" << str1 << "\") is " << num1 << '\n';
    cout << "atoi(\"" << str2 << "\") is " << num2 << '\n';
    cout << "atoi(\"" << str3 << "\") is " << num3 << '\n';
  
    return 0;
}

C




// C program to demonstrate the functioning of 
// the ATOI() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
  
    char* str1 = "42";
    char* str2 = "3.14159";
    char* str3 = "31337 geek";
  
    int myint1 = atoi(str1); // explicit type casting
    int myint2 = atoi(str2); // explicit type casting
    int myint3 = atoi(str3); // explicit type casting
  
    printf("stoi(%s) is %d \n", str1, myint1);
    printf("stoi(%s) is %d \n", str2, myint2);
    printf("stoi(%s) is %d \n", str3, myint3);
  
    return 0;
}

Output:

atoi("42") is 42
atoi("3.14159") is 3
atoi("31337 geek") is 31337 

stoi() vs atoi()

1. atoi() is a legacy C-style function. stoi() is added in C++ 11. 

2. atoi() works only for C-style strings (character array and string literal), stoi() works for both C++ strings and C style strings

3. atoi() takes only one parameter and returns integer value.

int atoi (const char * str); 

4. stoi() can take up to three parameters, the second parameter is for starting index and the third parameter is for the base of the input number.

int stoi (const string&  str, size_t* index = 0, int base = 10); 

Exercise: Write your own atof() that takes a string (which represents a floating-point value) as an argument and returns its value as double.

C++




#include <cstdlib>
#include <iostream>
using namespace std;
  
int main()
{
    const char* str1 = "42.245";
  
    double num1 = atof(str1); // explicit type casting
    
    cout << "atof(\"" << str1 << "\") is " << num1 << '\n';
    return 0;
}

Output:

atof("42.245") is 42.245 // atof is argument-to-float

This article is contributed by Siffi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!