Knowledge variety conversion is a not unusual procedure this is broadly utilized in programming. There are a number of circumstances the place you want to transform a variable of 1 information variety to some other. You’ll do the conversion of information sorts in two tactics: Implicit variety conversion (performed through the compiler) and Particular variety conversion (performed manually). Lots of the programming languages supply in-built learn how to carry out particular variety conversion.
Changing information from an integer layout to a string permits you to carry out quite a lot of string operations at the information. From time to time mathematics operations grow to be a tedious job in comparison to string operations. For example, imagine the next instance to print the present date.
The usage of String Operation:
string 12 months = “2021”;
cout << “These days’s date is: 31/05/” << 12 months.substr(2);
Output:
These days’s date is: 31/05/21
The usage of Mathematics Operation:
int 12 months = 2021;
int formattedYear = 12 months – 2000;
cout << “These days’s date is: 31/05/” << formattedYear;
Output:
These days’s date is: 31/05/21
Within the above instance, the primary means that makes use of a string operation to print the present date is extra handy than the second one means which makes use of an mathematics operation.
On this article, you are going to discover how you’ll be able to convert an integer right into a string in C++.
Learn how to Convert Int to String in C++
There are 3 other ways during which you’ll be able to carry out conversion of an int to thread in C++. On this phase, you are going to glance into a lot of these 3 strategies intimately.
1. The usage of the Stringstream Elegance
The stringstream magnificence permits enter/output operations on streams according to strings. It could possibly carry out parsing in quite a lot of tactics. The stringstream magnificence is integrated within the “sstream” header record. It comprises the next elementary strategies within the stringstream magnificence:
- Operator “>>”: The “>>” operator within the stringstream magnificence is used to learn or extract formatted information from a circulation object
- Operator “<<”: The “<<” operator within the stringstream magnificence is used so as to add formatted information right into a circulation object
- str(): The str() means of the stringstream magnificence is used to assign or retrieve values of the underlying string object
- transparent(): The transparent() means of the stringstream magnificence is used to transparent the contents of the circulation
The “<<” and “>>” operators can convert int to thread in C++. The syntax to insert and extract information the usage of those operators is:
// claim a circulation object
stringstream string_object_name;
// insert operation
string_object_name << 50;
// extract operation
string_object_name >> my_var;
Description of the syntax
- string_object_name: That is the title of the stringstream object that was once declared to accomplish the enter/output operations on strings.
- “<<”: This operator inserts the price at the right-hand aspect to the stringstream object.
- “>>”: This operator extracts the price of the stringstream object and retail outlets it in a string variable at the right-hand aspect.
Instance
Enter:
str_s << 20
str_s >> my_string
Output: 20
Clarification:
You insert the integer 20 into the string object str_s and extracted it to a string variable my_str, which in the end converts the integer 20 into the string “20”.
The next instance illustrates the running of stringstream magnificence to transform int to thread in C++:
#come with <iostream>
#come with <sstream> // header record for stringstream
the usage of namespace std;
int major()
{
// initialize an integer
int num = 20;
// making use of the stringstream magnificence
// claim a circulation object
stringstream circulation;
circulation << num;
// initializing a string
string str;
circulation >> str;
cout << “n”
<< “Worth of num is : ” << num << “n”;
cout << “String illustration of the num after making use of stringstream is : ” << str;
go back 0;
}
Within the above instance, it converts the integer 20 into the string “20”. The circulation object plays insertion and extraction operations the usage of the “<<” and “>>” operators. The integer 20 is first inserted into the thing circulation after which extracted to a string variable str.
2. The usage of the to_string() Manner
The following means on this listing to transform int to thread in C++ is through the usage of the to_string() serve as. This serve as is used to transform no longer simplest the integer however numerical values of any information variety right into a string.
The syntax of the to_string() serve as is:
string to_string (int num);
string to_string (lengthy num);
string to_string (lengthy lengthy num);
string to_string (unsigned num);
string to_string (unsigned lengthy num);
string to_string (unsigned lengthy lengthy num);
string to_string (flow num);
string to_string (double num);
string to_string (lengthy double num);
Description of the syntax
- The to_string() means is integrated within the header record of the category string, i.e., <string> or <cstring>.
- This serve as takes a numerical worth as a parameter that must be transformed right into a string. This numerical worth may also be of any information variety, together with integer, flow, double, lengthy double, and so forth.
Go back Worth
This serve as returns a string object akin to the price handed as a controversy.
Instance
Enter: x = 10;
to_string(x);
Output: 10
Clarification:
The variable conserving an integer worth i.e. 10 is handed to the to_string() means which returns a corresponding string “10”.
The next instance illustrates the running of to_string() serve as in C++:
#come with <iostream>
#come with <string> // header record for string
the usage of namespace std;
int major()
{
// initializing integers
int num1 = 21;
int num2 = 2122;
int num3 = 212232;
// Changing int to thread
string str1 = to_string(num1);
// Changing int to thread
string str2 = to_string(num2);
// Changing int to thread
string str3 = to_string(num3);
// print the transformed strings
cout << “String illustration of num1: ” << str1 << ‘n’;
cout << “String illustration of num2: ” << str2 << ‘n’;
cout << “String illustration of num3: ” << str3 << ‘n’;
go back 0;
}
Within the above instance, there are 3 integers, num1, num2, and num3. To transform them right into a string, you have got handed each and every integer to the to_string() serve as and get their string illustration. Observe that to make use of the capability of the string magnificence, it’s important to upload the <string> header record.
3. The usage of spice up::lexical_cast
The spice up::lexical_cast means is some other approach to convert an integer right into a string. This serve as is outlined within the library “spice up/lexical_cast.hpp” and will carry out interconversions of various information sorts together with flow, integer, double, and string.
Observe: You want to put in the Spice up libraries first, prior to executing this approach to convert int to thread in C++.
The syntax of the spice up::lexical_cast means is:
spice up::lexical_cast<data-type>(argument)
Description of the Syntax
- data-type: That is the kind during which the argument must be transformed. To transform an integer to a string, you will have to specify the information variety as a string.
- argument: That is the price that must be transformed. To transform an integer to a string, the argument will have to be an integer worth.
Instance
Enter: num = 50
spice up::lexical_cast<string> (num)
Output: 50
Clarification:
It passes the integer 50 as a controversy to the lexical_cast operator, which converts this integer into the corresponding string “50”.
The next instance illustrates the running of spice up::lexical_cast to transform int to thread in C++:
#come with <bits/stdc++.h>
#come with <spice up/lexical_cast.hpp>
the usage of namespace std;
int major()
{
//initialize the integer
int num = 50;
// convert int to thread
string str = spice up::lexical_cast<string>(num);
// print the transformed string
cout << “The string illustration of the integer num is :” << str << “n”;
go back 0;
}
Within the above instance, the integer 50 is transformed right into a string through passing it as a controversy to the lexical_cast operator.
Learn how to Claim and Initialize Strings in C++?
In C++, strings are items of the std::string magnificence that permit you to retailer and manipulate sequences of characters.
- To claim a string variable, you’ll be able to use the next syntax:
std::string str; // claim an empty string variable
- To initialize the string with a price, use one of the vital following strategies:
std::string str1 = “Hi, global!”; // initialize a string with a string literal
std::string str2(“It is a C++ string.”); // initialize a string with a constructor
std::string str3 {‘A’, ‘B’, ‘C’}; // initialize a string with a listing of characters
- To concatenate strings the usage of the + operator, use the next syntax:
std::string str4 = “Hi” + “, ” + “global” + “!”; // concatenate strings
- Changing an Integer to a String
- The usage of to_string serve as
In C++, you’ll be able to use the to_string serve as to transform an integer to a string. This serve as is a member of the std namespace, and it takes an integer worth as its argument and returns a string.
int num = 123;
std::string str = std::to_string(num);
Right here, the to_string() means is used to transform the integer worth 123 right into a string.
The to_string serve as is a part of the C++11 same old, so it would possibly not paintings on older compilers that don’t beef up this same old.
- The usage of sprintf( ) serve as
We will use the sprintf serve as to transform an integer to a string:
int num = 123;
char buffer[10];
std::sprintf(buffer, “%d”, num);
std::string str(buffer);
The sprintf serve as is used to put in writing the integer worth 123 to a personality array buffer, after which the nature array is transformed to a string the usage of the std::string constructor
When and Why Do We Want to Convert Int to String in C++?
In C++, an int is a knowledge variety that retail outlets integer values, whilst a string is a knowledge variety that retail outlets text-based values. It’s every so often essential to transform an int to a sequence when the person calls for a string illustration of a numerical worth. Conversion of an int to a string permits the person to accomplish string-specific operations at the newly created collection, equivalent to concatenation or formatting. Moreover, an int-to-string mutation is advisable when the person wishes to avoid wasting an int as textual content in a record or when exhibiting an int to the console for visible functions.
Changing integers to strings in C++ is a not unusual job and may also be accomplished the usage of the stringstream magnificence, which supplies a stream-based strategy to convert numbers to strings. The elemental concept in the back of this magnificence is to create a circulation of characters after which upload the numbers as though they had been strings on their very own. As soon as the conversion is whole, the ensuing circulation may also be learn as a string. This method is beneficial once we wish to convert an integer right into a line and go it as a parameter to a serve as or retailer it in a knowledge construction.
Output:
Examples for Quite a lot of Knowledge Varieties in C++
int age = 25;
On this instance, the age variable is said as an integer and initialized with the price of 25.
-
Floating-Level Knowledge Sort:
flow pi = 3.14;
On this instance, the pi variable is said as a floating-point variable and initialized with the price of three.14.
double wage = 10000.50;
On this instance, the wage variable is said as double and initialized with the price of 10000.50.
char grade = ‘A’;
On this instance, the grade variable is said as a personality and initialized with the price of ‘A’.
std::string title = “John”;
On this instance, the title variable is said as a string and initialized with the price of “John”.
lengthy inhabitants = 1000000L;
On this instance, the inhabitants variable is said as lengthy and initialized with the price of 1000000L.
unsigned int rely = 10;
On this instance, the rely variable is said as an unsigned integer and initialized with the price of 10.
Ultimate Ideas!
To sum up briefly, on this article, you have got discovered in regards to the significance of data-type or variety conversions in C++. You noticed 3 other learn how to convert an integer information variety to a string information variety in C++. Changing an integer to a string information variety permits you to adjust the digits in an integer and carry out a number of different operations on an integer which will have been imaginable simplest on a string. You understood the stringstream magnificence, to_string() means, and the lexical_cast approach to convert integer information sorts to thread.
If you wish to be told extra about such basic ideas in C++, you will have to for sure take a look at our whole information on C++ for inexperienced persons.
Why forestall right here? If you wish to be told extra about quite a lot of different gear, frameworks, and programming languages, you’ll be able to soak up any of our loose on-line classes taught through trade mavens with years of information and enjoy. Take a look at those loose on-line classes.
It additionally is sensible to be told some of the trending and in-demand tool construction abilities – Complete Stack Internet Building. Simplilearn makes it a complete lot more straightforward for you. You’ll soak up the 9-month mentor-led Complete Stack Internet Building path. On the finish of this path, you are going to have discovered a number of trending gear and frameworks together with Java and its frameworks equivalent to Hibernate, Spring, JPA, and so forth., DevOps, Agile, front-end applied sciences equivalent to HTML, CSS, JS, Servlets, and so forth.
When you’ve got any queries associated with this newsletter on “Int to String in C++” or another ideas for us, please be at liberty to drop a remark within the remark field and our mavens gets again to you on the earliest.
Satisfied Studying!
FAQs
1. Learn how to convert int right into a string?
There are quite a lot of strategies we will be able to make use of to transform an integer right into a string in c++:
a) The usage of the Stringstream Elegance
b) The usage of the to_string() Manner
c) The usage of spice up::lexical_cast
2. What’s to_string in C++?
to_string is a integrated serve as in C++ that permits changing numerical information sorts, equivalent to integers or floating-point numbers, into their corresponding string representations.
3. Learn how to convert int to thread in C++ the usage of Sstream?
To transform an integer to a string the usage of Sstream, practice those steps:
a) Come with the <sstream> header to make use of the Sstream library.
b) Create an std::stringstream object.
c) Use the << operator to insert the integer into the stringstream.
d) Extract the string the usage of the str() means of the stringstream.
4. What’s itoa and atoi in C++?
itoa: itoa is a C Usual Library serve as used to transform an integer to a string. It isn’t a part of the C++ Usual Library, however it’s to be had in lots of C++ implementations because of its in style use.
atoi: atoi is a C Usual Library serve as used to transform a string to an integer. Like itoa, it’s not a part of the C++ Usual Library however is to be had in lots of C++ implementations.
5. How do you utilize Itoa ()?
To make use of itoa() to transform an integer to a string in C++, practice those steps:
a) Come with the <cstdlib> header to make use of the C Usual Library serve as.
b) Claim a personality array (char buffer) to retailer the ensuing string.
c) Name the itoa() serve as, passing the integer, the nature array (buffer), and the bottom (generally 10 for decimal).
d) The integer shall be transformed and saved as a string within the personality array.
supply: www.simplilearn.com