Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer to string conversion / integer-string concatenation in C++ - more compact solutions?

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?

like image 397
daj Avatar asked Dec 20 '11 14:12

daj


People also ask

How do I append an int to a string?

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.

How do you convert int to string manually?

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.

How do you concatenate strings?

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.

How do I concatenate a number to a string in C++?

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.


1 Answers

#include <string>

String to integer: int n = std::stoi(s);

Integer to string: std::string s = std::to_string(n);

like image 86
Kerrek SB Avatar answered Nov 12 '22 21:11

Kerrek SB