Sunday, July 3, 2022
HomeArtificial IntelligenceThe best way to convert Int to String in C++

The best way to convert Int to String in C++


Among the many multitude of operations that may be carried out in C++, information sort conversion resembling int to string C++. It helps implicit in addition to the express sort of conversions. Implicit sort casting is finished robotically by the C++ compiler relying on the precedence of the datatypes within the run time. Alternatively, express conversions are carried out by the person as per this system necessities. For instance, if there’s an addition between a floating-point and an integer worth, the end result will at all times be in a floating-point. It is because of implicit sort conversion. We are able to explicitly convert this floating-point end result to an integer. It will likely be known as express sort conversion. 

This weblog offers with the conversion of int to string C++. We are going to have a look at numerous strategies that come in useful whereas changing int to string C++ and find out about their implementation. 

3 methods of changing int to string C++ 

There are 3 ways in which you’ll be able to convert int to string c++. They’re as follows:

  • Conversion of an integer right into a string with the assistance of to_string() methodology
  • Conversion of an integer right into a string with the assistance of stringstream class
  • Conversion of an integer right into a string with the assistance of a enhance.lexical solid

Let’s perceive every of the above listed methods of changing an int to string c++ one after the other. 

Conversion of an integer right into a string with the assistance of to_string() methodology

The best and most typical manner of changing a variable or worth of another information sort into string sort explicitly is utilizing the to_string() methodology. It takes one parameter for the variable or worth which must be transformed to a string. Right here’s the syntax for utilizing the to_string() methodology.

Syntax:

str s = to_string(var);

Right here, ‘var’ is the variable that must be transformed into string sort and ‘s’ is the transformed string variable.

Undergo the next instance to get a transparent concept. 

Instance:

// Together with important header information
#embody <iostream>  
#embody <string>  
#embody <cstring>

utilizing namespace std;  
// driver operate
int major()  
{  
 int n;  
 cout << "Enter an integer quantity to be transformed into string: ";
 cin >> n;
 string st = to_string(n);    // Changing int to string
 cout << "string worth of the entered integer is : " << st << endl;  
 
 // Checking for profitable string conversion 
  cout << typeid(st).title();
  return 0;
}  

Output:

As seen within the output of the above code, the typeid(st).title provides string. Therefore, the integer n has been efficiently transformed into string st utilizing the to_string() operate. Apart from, had it not been a profitable conversion, the results of the to_string() methodology wouldn’t have been saved in a string sort variable ‘st’ within the first place, relatively it could have raised an error. 

Conversion of an integer right into a string with the assistance of stringstream class

One other most typical manner of changing an integer right into a string is utilizing the stringstream class. This stream class is outlined within the header file <sstream> itself and used for finishing up the enter and output operations on string-based streams. The next operators of C++ enable insertion and extraction of knowledge into and from the information, respectively. 

  • >> (Extraction) Operator: This operator is used for fetching the information from the string stream. For instance: StrStream >> 11;
  • << (Insertion) Operator: This operator is used for placing the information into the string stream. For instance: StrStream << 11;

Syntax:

Stringstream st;             // declaring stringstream object
st << var;                      // writing into the stream
string s;                        // declaring a string variable to retailer the transformed string
st >> s;                        // extracting the string from stream

Right here, ‘st’ is the thing of stringstream class that’s used for writing into the stream and extracting from the stream, ‘var’ is the variable that holds the worth to be put into the stream, and ‘s’ is the string variable that shops the extracted string.

Allow us to see how we are able to convert int to string in C++ with the assistance of stringstream class by way of the instance given under.

Instance:

// Together with important header information
#embody <iostream>  
#embody<sstream>  

utilizing namespace std;  

// driver operate
int major() {  
  int var;  
  cout << "Enter an integer worth : ";  
  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 worth is : " << var << "n";  
  cout << "String illustration of an this worth is : " << svar;   
  return 0;
}  

Output:

Right here, we’re utilizing the stringstream class which is imported into this system after we embody the <sstream> header file. This class transformed the enter integer worth right into a string. Right here once more, the truth that storing the extracted worth in a string variable, ‘svar’ is elevating no error signifies profitable string conversion of the integer worth. Other than that, you may search the datatype of the transformed variable utilizing typeid().title(svar) as finished within the instance of changing an integer to string utilizing to_string() operate.

We are able to use this approach to do the opposite manner spherical as properly, i.e. we are able to convert a string worth into an integer worth utilizing stringstream. Take into account operating the next exemplar code for readability.

//Together with important header information

#embody <iostream>  
#embody<sstream>  

utilizing namespace std;  

// driver operate
int major()  
{  
  string str_num;
  cout << "Enter a string quantity to be transformed 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 within the type of integer
  cout << "The string you entered is : " << str_num << endl;  
  cout << "Integer worth of this string is : " << num;  
  return 0;
}  

Output:

Right here, a string enter is taken from the person after which, it’s transformed into an integer utilizing the stringstream class. The variable ‘num’ holds the transformed integer worth. Should you use the typeid(num).title(), it’ll return the datatype of the variable ‘num’. 

Conversion of an integer right into a string with the assistance of enhance.lexical solid

The third manner of changing an integer worth right into a string worth in C++ is utilizing lexical_cast() operator of enhance library. The best way this solid is used for string conversions, it may be used for different information sort conversions fairly properly, too. For with the ability to use the enhance.lexical solid, together with the enhance/lexical_cast header file is important, else the compiler will increase an error. 

Syntax:

string st = enhance::lexical_cast<string>(val)   

Right here, ‘val’ is the integer variable or the worth that’s required to be transformed into string sort. Lexical_cast operator takes the variable or worth, ‘val’ to be transformed right into a string because the operand. On this case, the datatype of ‘val’ is int. 

Allow us to perceive its implementation with the assistance of an instance.

Instance:

//Together with important header information
#embody <iostream>  
#embody <enhance/lexical_cast.hpp>  //together with the lexical solid operator of enhance library 
#embody <string>
#embody <bits/stdc++.h>

utilizing namespace std;  

// driver operate
int major()  
{  
 int var; 
 cout << "Enter an integer: ";
 cin >> var;
 string str = enhance::lexical_cast<string>(var);  //Utilizing lexical_cast for conversion of int to string
 cout << endl << "string worth of the entered integer is :" << str;  
 return 0;
}  

Output:

As seen from the above piece of code and its corresponding output, the enhance::lexical_cast efficiently converts the integer right into a string. This methodology may also be utilized for changing a string into an integer. We simply want to alter the datatype within the angular brackets of lexical_cast. Therefore, for changing a string into an integer, you’ll have to use the next syntax:

Syntax:

int n = enhance::lexical_cast<int>(st);

Right here, ‘n’ is the integer variable chargeable for storing the transformed integer worth. ‘st’ is the string variable to be transformed into integer. <int> signifies that the argument needs to be transformed into integer sort. 

Check out the instance given under to get some readability on the identical. 

Instance:

//Together with important header information
#embody <iostream>  
#embody <enhance/lexical_cast.hpp>    //together with the enhance/lexical_cast header file
#embody <bits/stdc++.h>

utilizing namespace std;  

// driver operate
int major()  
{  
 string str;
 cout << "Enter the string to be transformed into an integer : ";
 cin >> str;
 int i = enhance::lexical_cast<int>(str);    // Utilizing lexical_cast for changing string to int
cout << endl << "Integer worth of the entered string is : " << i;
return 0;
}  

Output:

Right here, the string ‘234’ has been transformed into integer sort. For affirmation, you may examine the datatype of variable ‘i’ utilizing type_id(i).title() in C++. 

When and why do we have to convert int to string in C++

For the eventualities in programming the place we have to deal with a quantity or integer as a string, we explicitly convert it into string sort with the assistance of the above mentioned 3 ways. At instances, performing arithmetic operations turns into a nut job and utilizing string operations of their stead could be useful. To have the ability to use string operations on an integer variable or worth, we’re first required to transform right into a string. Suppose, we’ve got to write down a program to print the present date, then you definately would need to use a string operation relatively than a tedious arithmetic operation for a process so simple as displaying the present date in dd/mm/yy format. Let’s now observe this state of affairs from each factors of view through coding.

// Utilizing string

#embody <iostream>
#embody <string.h>

utilizing namespace std;

int major()
{
    string yr = "2022";    // declaring yr (yr) as a string
    cout  <<  "The date right now is: 09/06/" <<  yr.substr(2) << endl;    //1
    return 0;
}

Output:

In line 1, we’ve got used the substr(2) operate of string class to extract the final two characters of the string yr to match the given format of dd/mm/yy. Now, allow us to see how we are able to do the identical utilizing arithmetic operations.

// Utilizing integer

#embody <iostream>

utilizing namespace std;

int major()
{
  // declaring two int variables
   int yr;     // one for  storing the present yr
    int format_yr;    // one other for storing the formatted yr
    yr = 2022;
    format_yr = yr - 2000;
    cout << "Immediately's date is: 09/06/" << format_yr;    //1
    return 0;
}

Output:

We are able to see that whether or not we deal with yr as a string or as an integer, there isn’t a distinction within the outputs, however the latter makes us write an additional line of code for getting the specified format of date. This was relatively fairly a easy instance during which treating ‘yr’ as an integer as an alternative of a string doesn’t make a lot distinction to the code. However, for the conditions the place a cumbersome set of arithmetic operations could be changed by a single and simpler string operation or operate, it’s higher to transform that integer into string.  Therefore, within the above instance, although we declare yr as int, we are able to convert it right into a string whereas displaying it to get the specified format. 

Conclusion

By now you’ve gotten gained a complete understanding of easy methods to convert int to string in C++. As you already know, there are two forms of conversions in C++, implicit sort and express sort. An int to string conversion is at all times an express sort casting. To wrap issues up, we’ve got discovered that there are 3 ways in C++ for performing an int-to-string conversion – to_string() methodology, string stream class, and enhance::lexical_cast<string>(). We now have additionally discovered in regards to the syntax and implementation of every of those strategies, together with examples. A few these methods are helpful in lots of different information sort conversions as properly. As an example, the stringstream class may also be used for a string-to-float conversion. You will need to be aware that earlier than calling any operate or methodology, we should be sure that its respective header file has been included in this system.  

FAQs

  • Can you exchange int to string?

Sure, we are able to simply convert an int to string. Whether or not it’s C++ or another programming language, there’s no less than a method in every that permits you to convert an integer right into a string and vice versa. The three ways in which can be utilized for an int to string conversion are – utilizing to_string() methodology, utilizing stringstream class, and utilizing lexical_cast<string> operator of the enhance library in C++

  • Can you exchange int to string in C?

Sure, as talked about within the reply to the earlier query, we’ve got the supply to transform an int to a string in C. The 2 capabilities that we are able to use for such a conversion in C are sprintf() and itoa().

  • What’s one of the simplest ways to transform int to string?

The best manner of changing int to string is utilizing std::to_string(n).It takes the integer variable or worth to be transformed right into a string as its argument. Aside from this, we are able to additionally 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 () methodology of C++ is used to transform a string to an integer. The C++ programmers typically use this operate in parsing out integers from strings. For utilizing stoi, you’re required to specify three issues which might be handed as its parameter

stoi (string, place, string_base)

The primary argument is the string that’s wanted to be transformed into an integer. The second is the place which is definitely an identifier for the beginning place of the integer within the string to be parsed. The final one is the string_base which defines the numerical base for the string handed, resembling 2 for binary, 10 for decimal (base 10), and so forth.

NOTE: When you’re working with a string of numerical base 10, you needn’t specify something aside from the string itself. 

Sure, stoi is a part of STD. In your info, STD stands for ‘normal’ and it’s a namespace whose members are utilized in a C++ program as per the programmer’s necessities. The namespace std consists of members like cin, cout, endl, stoi, and others. It’s current within the iostream.h header information itself, however we nonetheless want to write down ‘utilizing namespace std;’ because it permits us to make use of the identical names for capabilities, variables and lessons below completely different scopes. The stoi () operate of std is utilized in a string to integer conversion. 

  • What can I exploit as an alternative of stoi in C++?

Utilizing one other C++ std member atoi is equal to utilizing stoi for string to int conversions in C++. Nevertheless, we can not use the atoi() operate until we embody the cstdlib header file in our C++ program. Just like the stoi(n) operate, atoi(n) additionally takes just one parameter for the string to be transformed into an integer. 

There are some extra alternate options to utilizing stoi for string to int conversion in C++, for instance, we are able to go for the stringstream class methodology for a similar. If not stringstream, we are able to additionally go for enhance::lexical_cast<int>() methodology for a string to int conversion in C++.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments