Converting Strings to Numbers in C/C++ – GeeksforGeeks

Converting numbers to strings or vice-versa is a bit confusing in itself. We may have to perform such conversions while working with numbers and strings together. Despite being simple operations, many coders either fail or get confused while doing this.  

Before knowing how we should convert string to numbers what is the need for conversion : 

You’ll get an error if you try to input a value that isn’t acceptable with the data type. Both C/C++ is a strongly typed languages. You’ll get an error if you try to input a value that isn’t acceptable with the data type. Not just in inputs but you will get an error while performing operations. There is a fair chance of getting both syntax and logical errors.

For example, assume we had a numeric string “673” that we want to convert to a numeric type. We’ll need to utilize a function that converts a string to an integer and returns 673 as the numeric value.

Furthermore, converting a text to an integer is more difficult than converting doubles to integers using type casting. We are not allowed to perform type casting because int and string both are not in the same Object hierarchy.

For example, you cannot do this since it will give error

C++




#include <string>

using namespace std;

  

int main() {

   string str = "7";

   int num;

  

   num = (int) str;

}



The error after compiling will be:

hellp.cpp:9:10: error: no matching conversion for C-style cast from ‘std::__1::string’ (aka
    ‘basic_string<char, char_traits<char>, allocator<char> >’) to ‘int’
 num = (int) str;
       ^~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string:875:5: note: candidate function
  operator __self_view() const _NOEXCEPT { return __self_view(data(), size()); }
  ^
1 error generated.

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.

To use it, first, add the line #include <sstream> to the start of your program to include the sstream library.

The stringstream is then added and a stringstream object is created, which will retain the value of the string you want to convert to an int and will be utilized during the conversion process.

To extract the string from the string variable,  use <<  operator.

Next, you input the newly converted int value to the int variable using the >> operator.

Example:

CPP




#include <iostream>

#include <sstream>

using namespace std;

  

int main()

{

    string s = "12345";

  

    

    stringstream geek(s);

  

    

    

    int x = 0;

    geek >> x;

  

    

    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. 

GeeksforGeeks-CPP-Foundation-Course

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.

C++




  

#include <iostream>

using namespace std;

  

int main()

{

    const char* str = "12345";

    int x;

    sscanf(str, "%d", &x);

    

    cout << "\nThe value of x : " << x << endl;

    

    return 0;

}

  



C




  

#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

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

C




#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;

}



Output

The value of x : 12345.540039

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. This approach is popular in current versions of C++, and it was first introduced in C++11.And if you observe stoi() a little closer you will find out that it stands for:

   s    to     i()

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

Example:

CPP




#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

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:

C++14




#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);

    int num2 = atoi(str2);

    int num3 = atoi(str3);

  

    cout << "atoi(\"" << str1 << "\") is " << num1 << '\n';

    cout << "atoi(\"" << str2 << "\") is " << num2 << '\n';

    cout << "atoi(\"" << str3 << "\") is " << num3 << '\n';

  

    return 0;

}



C




#include <stdio.h>

#include <stdlib.h>

int main()

{

  

    char* str1 = "42";

    char* str2 = "3.14159";

    char* str3 = "31337 geek";

  

    int myint1 = atoi(str1);

    int myint2 = atoi(str2);

    int myint3 = atoi(str3);

  

    printf("atoi(%s) is %d \n", str1, myint1);

    printf("atoi(%s) is %d \n", str2, myint2);

    printf("atoi(%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);

    

    cout << "atof(\"" << str1 << "\") is " << num1 << '\n';

    return 0;

}



Output

atof("42.245") is 42.245

4. Using For Loop to convert Strings into number

C++




for ( int i = number.length() -1 ; i >= 0 ; i-- ) {

    int power = number.length() - i -1;

    newNumber += (std::pow( 10.0,  power) * (number[i] - '0'));

}



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