How to do integer -> string conversion has been answered many times on the internet... however, I'm looking for the most compact "C++-way" to do this.
Since you're able to concatenate strings using the overloaded + operator, it would be preferable to be able to do something along the lines of the python-ish x = (stringVariable + str(intVariable)) concatenation, but I don't know if there's a canonical way to do this in C++.
The most common solutions I see are:
stringstream: If possible, it would be nice not to have 3 lines of code (declaration, writing to the stream, conversion to string) just to concatenate some letters and numbers.
itoa: this works, but I'm looking for a canonical C++ solution. Also, I think itoa is technically non-standard although I could be wrong.
boost format / boost lexical cast: this works too, but is there nothing in vanilla C++ that does the job?
The easiest way to convert int to String is very simple. Just add to int or Integer an empty string "" and you'll get your int as a String. It happens because adding int and String gives you a new String. That means if you have int x = 5 , just define x + "" and you'll get your new 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.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.
#include <string>
String to integer: int n = std::stoi(s);
Integer to string: std::string s = std::to_string(n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With