I need to create a string of 100 A characters.
Why does the following
std::string myString = {100, 'A'};
give different results than
std::string myString(100, 'A');
?
std::string myString = {100, 'A'};
is initialization using initializer list. It creates a string with 2 characters: one with code 100 and 'A'
std::string myString(100, 'A');
calls the following constructor:
string (size_t n, char c);
which creates a string with 100 'A's
char with the value 100; it's ASCII if your system treats char values as ASCII. While that's quite common, it's not required by the C++ language definition, and there are systems where it's not true.std::string s = { 100, 'A' }; is undefined behaviour? Wouldn't that invalidate most of the intention of creating the uniform initializer syntax in C++11?CHAR_MAX is required to be at least 127, so 100 is a valid value of char regardless of what glyph it represents (if any -- not all values of char necessarily represent characters at all, so in theory you might have trouble printing it).char is an arithmetic type as well as a character representation; there's nothing wrong with assigning 100 to a char object.The first initializes it to values of 100 and A and the second calls a constructor overload of std::string.
'A' characters.
std::string myString{100,'A'};initializer_listconstructor takes precedence over all others. The=sign makes no difference here. See demo.std::string myString(100, 'A');