Append int to std::string
TL;DR operator+=
is a class member function in class string
, while operator+
is a template function.
The standard class template<typename CharT> basic_string<CharT>
has overloaded function basic_string& operator+=(CharT)
, and string is just basic_string<char>
.
As values that fits in a lower type can be automatically cast into that type, in expression s += 2
, the 2 is not treated as int
, but char
instead. It has exactly the same effect as s += '\x02'
. A char with ASCII code 2 (STX) is appended, not the character '2' (with ASCII value 50, or 0x32).
However, string does not have an overloaded member function like string operator+(int)
, s + 2
is not a valid expression, thus throws an error during compilation. (More below)
You can use operator+ function in string in these ways:
s = s + char(2); // or (char)2
s = s + std::string(2);
s = s + std::to_string(2); // C++11 and above only
For people concerned about why 2 isn't automatically cast to char
with operator+
,
template <typename CharT>
basic_string<CharT>
operator+(const basic_string<CharT>& lhs, CharT rhs);
The above is the prototype[note] for the plus operator in s + 2
, and because it's a template function, it is requiring an implementation of both operator+<char>
and operator+<int>
, which is conflicting. For details, see Why isn't automatic downcasting applied to template functions?
Meanwhile, the prototype of operator+=
is:
template <typename CharT>
class basic_string{
basic_string&
operator+=(CharT _c);
};
You see, no template here (it's a class member function), so the compiler deduces that type CharT is char
from class implementation, and int(2)
is automatically cast into char(2)
.
Note: Unnecessary code is stripped when copying from C++ standard include source. That includes typename 2 and 3 (Traits and Allocator) for template class "basic_string", and unnecessary underscores, in order to improve readability.
Easiest way to convert int to string in C++
C++11 introduces std::stoi
(and variants for each numeric type) and std::to_string
, the counterparts of the C atoi
and itoa
but expressed in term of std::string
.
#include <string>
std::string s = std::to_string(42);
is therefore the shortest way I can think of. You can even omit naming the type, using the auto
keyword:
auto s = std::to_string(42);
Note: see [string.conversions] (21.5 in n3242)
Converting an int to std::string
You can use std::to_string in C++11
int i = 3;
std::string str = std::to_string(i);
Why is appending an int to a std::string undefined behavior with no compiler warning in C++?
The problem is that in
logger->info("i has the following value: " + i);
you are not working with std::string
. You are adding an int
to a string literal, ie a const char[]
array. The const char[]
decays into a const char*
pointer in certain contexts. In this case, the int
advances that pointer forward by 1337 characters, which is way beyond the end of the string literal, and therefore undefined behavior.
You should get a better compiler that warns you about this, ie:
foo.cc:7:42: warning: offset ‘1337’ outside bounds of constant string [-Warray-bounds]
7 | foo("i has the following value: " + i);
| ^
You can use a std::string
literal like this:
#include <string>
using namespace std::literals;
void foo(std::string);
void bla() {
int i = 1337;
foo("i has the following value: "s + i);
}
and then you get a "nicer" error that "std::string + int" isn't a thing in C++:
foo.cc:8:40: error: no match for ‘operator+’ (operand types are ‘std::__cxx11::basic_string<char>’ and ‘int’)
8 | foo("i has the following value: "s + i);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^ ~
| | |
| std::__cxx11::basic_string<char> int
...
going on for 147 lines
After this, it should be obvious that what you want is this instead:
logger->info("i has the following value: "s + std::to_string(i));
Using std::string
literals avoids mistakes like this, because it turns warnings (which your compiler doesn't even give) into hard errors, forcing you to write correct code. So I recommend using the s
suffix for all strings.
Append an integer to std::wstring gives an error
The regular std::ostringstream
is not wide. The wstring
would like to be assigned a wide string.
You'll need std::wostringstream
How can I append int variable to string to print path of my DFS algorithm?
You declare a string
variable named path
, but your parameter is already named path
.
So path[i]
actually refers to the string
, not to the vector
.
Also, path[i]
is a const Node*
, so you must call it's function with : path[i]->getNodeID()
.
Related Topics
How to Save Two Camera's Data But Not Influence Their Picture-Acquire Speed
Lifetime of Object Is Over Before Destructor Is Called
Remote Debugging C++ Applications with Eclipse Cdt/Rse/Rdt
Difference Between Regex_Match and Regex_Search
How to Use Unicode Range in C++ Regex
Date/Time Conversion: String Representation to Time_T
Referencing Memory Operands in .Intel_Syntax Gnu C Inline Assembly
Using Visual Studio Project Properties Effectively for Multiple Projects and Configurations
Initialize a Vector to Zeros C++/C++11
Invalid Initialization of Non-Const Reference with C++11 Thread
What Does the Gcc Warning "Project Parameter Passing for X Changed in Gcc 7.1" Mean
When Pass a Variable to a Function, Why the Function Only Gets a Duplicate of the Variable
Writing a Matrix into a Single Txt File with Mpi
Undefined Reference to Mempcy@Glibc_2.14 When Compiling on Linux