Among the multitude of operations that can be performed in C++, data type conversion such as int to string C++. It supports implicit as well as the explicit type of conversions. Implicit type casting is done automatically by the C++ compiler depending on the priority of the datatypes in the run time. On the other hand, explicit conversions are carried out by the user as per the program requirements. For example, if there is an addition between a floating-point and an integer value, the result will always be in a floating-point. It is due to implicit type conversion. We can explicitly convert this floating-point result to an integer. It will be referred to as explicit type conversion.
This blog deals with the conversion of int to string C++. We will look at various methods that come in handy while converting int to string C++ and learn about their implementation. Before moving forward, you can brush up your skills with the help of a free online C++ tutorial.
Let’s get started!
3 ways of converting int to string C++
There are three ways in which you can convert int to string c++. They are as follows:
- Conversion of an integer into a string with the help of to_string() method
- Conversion of an integer into a string with the help of stringstream class
- Conversion of an integer into a string with the help of a boost.lexical cast
Let’s understand each of the above listed ways of converting an int to string c++ one by one.
Also Read: What are Strings in C++?
Conversion of an integer into a string with the help of to_string() method
The simplest and most common way of converting a variable or value of any other data type into string type explicitly is using the to_string() method. It takes one parameter for the variable or value which needs to be converted to a string. Here’s the syntax for using the to_string() method.
Syntax:
str s = to_string(var);
Here, ‘var’ is the variable that needs to be converted into string type and ‘s’ is the converted string variable.
Go through the following example to get a clear idea.
Example:
// Including essential header files
#include <iostream> #include <string> #include <cstring> using namespace std; // driver function
int main() { int n; cout << "Enter an integer number to be converted into string: "; cin >> n; string st = to_string(n); // Converting int to string cout << "string value of the entered integer is : " << st << endl; // Checking for successful string conversion cout << typeid(st).name(); return 0;
}
Output:
As seen in the output of the above code, the typeid(st).name gives string. Hence, the integer n has been successfully converted into string st using the to_string() function. Besides, had it not been a successful conversion, the result of the to_string() method wouldn’t have been stored in a string type variable ‘st’ in the first place, rather it would have raised an error.
Also Read: C++ Projects To Work On In 2022
Conversion of an integer into a string with the help of stringstream class
Another most common way of converting an integer into a string is using the stringstream class. This stream class is defined in the header file <sstream> itself and used for carrying out the input and output operations on string-based streams. The following operators of C++ allow insertion and extraction of data into and from the data, respectively.
- >> (Extraction) Operator: This operator is used for fetching the data from the string stream. For example: StrStream >> 11;
- << (Insertion) Operator: This operator is used for putting the data into the string stream. For example: StrStream << 11;
Syntax:
Stringstream st; // declaring stringstream object
st << var; // writing into the stream
string s; // declaring a string variable to store the converted string
st >> s; // extracting the string from stream
Here, ‘st’ is the object of stringstream class that is used for writing into the stream and extracting from the stream, ‘var’ is the variable that holds the value to be put into the stream, and ‘s’ is the string variable that stores the extracted string.
Let us see how we can convert int to string in C++ with the help of stringstream class through the example given below.
Example:
// Including essential header files
#include <iostream> #include<sstream> using namespace std; // driver function
int main() { int var; cout << "Enter an integer value : "; cin >> var; stringstream str; // declaring stringstream object str << var; // writing into the stream string svar; str >> svar; // extracting the string from stream cout << "\n" << "Entered integer value is : " << var << "\n"; cout << "String representation of an this value is : " << svar; return 0;
}
Output:
Here, we are using the stringstream class which is imported into the program when we include the <sstream> header file. This class converted the input integer value into a string. Here again, the fact that storing the extracted value in a string variable, ‘svar’ is raising no error indicates successful string conversion of the integer value. Apart from that, you can seek the datatype of the converted variable using typeid().name(svar) as done in the example of converting an integer to string using to_string() function.
We can use this way to do the other way round as well, i.e. we can convert a string value into an integer value using stringstream. Consider running the following exemplar code for clarity.
//Including essential header files #include <iostream> #include<sstream> using namespace std; // driver function
int main() { string str_num; cout << "Enter a string number to be converted into integer: "; cin >> str_num; stringstream strstream; // declaring stringstream object strstream << str_num; // writing string into the stream int num; strstream >> num; // extracting the string from stream in the form of integer cout << "The string you entered is : " << str_num << endl; cout << "Integer value of this string is : " << num; return 0;
}
Output:
Here, a string input is taken from the user and then, it is converted into an integer using the stringstream class. The variable ‘num’ holds the converted integer value. If you use the typeid(num).name(), it will return the datatype of the variable ‘num’.
Conversion of an integer into a string with the help of boost.lexical cast
The third way of converting an integer value into a string value in C++ is using lexical_cast() operator of boost library. The way this cast is used for string conversions, it can be used for other data type conversions pretty well, too. For being able to use the boost.lexical cast, including the boost/lexical_cast header file is necessary, else the compiler will raise an error.
Syntax:
string st = boost::lexical_cast<string>(val)
Here, ‘val’ is the integer variable or the value that is required to be converted into string type. Lexical_cast operator takes the variable or value, ‘val’ to be converted into a string as the operand. In this case, the datatype of ‘val’ is int.
Let us understand its implementation with the help of an example.
Example:
//Including essential header files
#include <iostream> #include <boost/lexical_cast.hpp> //including the lexical cast operator of boost library #include <string>
#include <bits/stdc++.h> using namespace std; // driver function
int main() { int var; cout << "Enter an integer: "; cin >> var; string str = boost::lexical_cast<string>(var); //Using lexical_cast for conversion of int to string cout << endl << "string value of the entered integer is :" << str; return 0;
}
Output:
As seen from the above piece of code and its corresponding output, the boost::lexical_cast successfully converts the integer into a string. This method can also be applied for converting a string into an integer. We just need to change the datatype in the angular brackets of lexical_cast. Hence, for converting a string into an integer, you will have to use the following syntax:
Syntax:
int n = boost::lexical_cast<int>(st);
Here, ‘n’ is the integer variable responsible for storing the converted integer value. ‘st’ is the string variable to be converted into integer. <int> indicates that the argument has to be converted into integer type.
Take a look at the example given below to get some clarity on the same.
Example:
//Including essential header files
#include <iostream> #include <boost/lexical_cast.hpp> //including the boost/lexical_cast header file
#include <bits/stdc++.h> using namespace std; // driver function
int main() { string str; cout << "Enter the string to be converted into an integer : "; cin >> str; int i = boost::lexical_cast<int>(str); // Using lexical_cast for converting string to int
cout << endl << "Integer value of the entered string is : " << i;
return 0;
}
Output:
Here, the string ‘234’ has been converted into integer type. For confirmation, you can check the datatype of variable ‘i’ using type_id(i).name() in C++.
When and why do we need to convert int to string in C++
For the scenarios in programming where we need to treat a number or integer as a string, we explicitly convert it into string type with the help of the above discussed three ways. At times, performing arithmetic operations becomes a nut job and using string operations in their stead can be helpful. To be able to use string operations on an integer variable or value, we are first required to convert into a string. Suppose, we have to write a program to print the current date, then you would want to use a string operation rather than a tedious arithmetic operation for a task as simple as displaying the current date in dd/mm/yy format. Let’s now observe this scenario from both points of view via coding.
// Using string #include <iostream>
#include <string.h> using namespace std; int main()
{ string yr = "2022"; // declaring year (yr) as a string cout << "The date today is: 09/06/" << year.substr(2) << endl; //1 return 0;
}
Output:
In line 1, we have used the substr(2) function of string class to extract the last two characters of the string yr to match the given format of dd/mm/yy. Now, let us see how we can do the same using arithmetic operations.
// Using integer #include <iostream> using namespace std; int main()
{ // declaring two int variables int yr; // one for storing the current year int format_yr; // another for storing the formatted year yr = 2022; format_yr = yr - 2000; cout << "Today's date is: 09/06/" << format_yr; //1 return 0;
}
Output:
We can see that whether we handle year as a string or as an integer, there is no difference in the outputs, but the latter makes us write an extra line of code for getting the desired format of date. This was rather quite a simple example in which treating ‘yr’ as an integer instead of a string doesn’t make much difference to the code. But, for the situations where a bulky set of arithmetic operations can be replaced by a single and easier string operation or function, it is better to convert that integer into string. Hence, in the above example, even though we declare year as int, we can convert it into a string while displaying it to get the desired format.
Conclusion
By now you have gained a comprehensive understanding of how to convert int to string in C++. As you know, there are two types of conversions in C++, implicit type and explicit type. An int to string conversion is always an explicit type casting. To wrap things up, we have learned that there are three ways in C++ for performing an int-to-string conversion – to_string() method, string stream class, and boost::lexical_cast<string>(). We have also learned about the syntax and implementation of each of these methods, along with examples. A couple of these ways are useful in many other data type conversions as well. For instance, the stringstream class can also be used for a string-to-float conversion. It is important to note that before calling any function or method, we must ensure that its respective header file has been included in the program.
FAQs
- Can you convert int to string?
Yes, we can easily convert an int to string. Whether it be C++ or any other programming language, there is at least one way in each that allows you to convert an integer into a string and vice versa. The three ways that can be used for an int to string conversion are – using to_string() method, using stringstream class, and using lexical_cast<string> operator of the boost library in C++.
- Can you convert int to string in C?
Yes, as mentioned in the answer to the previous question, we have the provision to convert an int to a string in C. The two functions that we can use for such a conversion in C are sprintf() and itoa().
- What is the best way to convert int to string?
The simplest way of converting int to string is using std::to_string(n).It takes the integer variable or value to be converted into a string as its argument. Other than this, we can also use a stringstream class or a lexical_cast operator for int to string conversion.
- What does stoi () do in C++?
stoi is an abbreviation of ‘String TO Integer’. This stoi () method of C++ is used to convert a string to an integer. The C++ programmers often use this function in parsing out integers from strings. For using stoi, you are required to specify three things that are passed as its parameter
stoi (string, position, string_base)
The first argument is the string that is needed to be converted into an integer. The second one is the position which is actually an identifier for the starting position of the integer in the string to be parsed. The last one is the string_base which defines the numerical base for the string passed, such as 2 for binary, 10 for decimal (base 10), and so on.
NOTE: When you are working with a string of numerical base 10, you need not specify anything except for the string itself.
- Is stoi part of STD?
Yes, stoi is part of STD. For your information, STD stands for ‘standard’ and it is a namespace whose members are used in a C++ program as per the programmer’s requirements. The namespace std includes members like cin, cout, endl, stoi, and others. It is present in the iostream.h header files itself, but we still need to write ‘using namespace std;’ as it enables us to use the same names for functions, variables and classes under different scopes. The stoi () function of std is used in a string to integer conversion.
- What can I use instead of stoi in C++?
Using another C++ std member atoi is equivalent to using stoi for string to int conversions in C++. However, we cannot use the atoi() function unless we include the cstdlib header file in our C++ program. Similar to the stoi(n) function, atoi(n) also takes only one parameter for the string to be converted into an integer.
There are some more alternatives to using stoi for string to int conversion in C++, for example, we can opt for the stringstream class method for the same. If not stringstream, we can also go for boost::lexical_cast<int>() method for a string to int conversion in C++.
Source: GreatLearning Blog