string to int in C++

Written by

Garvit Gulati

Many a times, we may need to extract numbers from a string and convert them to int in order to use the perform mathematical operations on them. We can do this by:

  1. Using string streams
  2. Using stoi() or atoi() functions

# Using string stream

String streams are similar to iostream and fstream but they allow us to perform I/O operations on string. Just like fstream, it has three main classes:

  1. stringstream: for both input and output
  2. ostringstream: for only output
  3. istringstream: for only input

To convert strings to numbers using string streams, we first push the number in the stream from the string and then using internal conversion extract it to an integer.

Implementation:

#include <iostream>
#include <string>	//for strings
#include <sstream>	//for stringstream
using namespace std;

int main()

{
	string s = "152";

	stringstream ob;	// object from the class stringstream

	ob << s;	//pushing ob in stream

	int x = 0;

	ob >> x;	//extracting

	// Now the variable x=152

	cout << "x=" << x;

	return 0;

}

Output

x=152

# Using stoi() or atoi()

Stoi()

It is a C++ 11 function that accepts a string as argument and returns its value. It can be used to convert strings to all types of numbers be it float, long or double. It is provided in the string header file.

Atoi()

It is C-style legacy function that accepts character array and returns its value. It works on only C-style strings i.e. character array and string literals. It is provided in the cstdlib header file.

Implementation(stoi()):

#include <iostream>
#include <string>
using namespace std;

int main()

{
	string s = "196";

	int x = stoi(s);

	cout << "x=" << x << "\n";

	s = "3.14";

	float f = stoi(s);

	cout << "f=" << f << "\n";

	return 0;

}

Output

x=196

f=3

Implementation(atoi()):

#include <iostream>
#include <cstring>	//for strcpy()
#include <cstdlib>	//for atoi()
using namespace std;

int main()

{
	char s[3];

	strcpy(s, "31");

	int x = atoi(s);

	cout << x;

	return 0;

}

Output

31
string to int in C++