'String plus Char - what is happening?
I'm just curious about what is going on when trying to add a char to a string.
Initially, I thought it would work like a concatenation but it didn't:
cout<<"ab"+'a'<<endl;
cout<<""+'a'<<endl;
Prints
However,
cout<<"bla"<<endl;
cout<<"ab"+'a'<<endl;
cout<<""+'a'<<endl;
Prints
Solution 1:[1]
String literals are char const[N]
(decays to char const *
), and char
is a small range integer type. You're doing pointer arithmetic.
Solution 2:[2]
The string is converted to a "char *", and then the ascii value of 'a' (96) is added to that character. You're now outputting characters beyond the end of the string.
If you're trying to concatenate two strings, see Append Char To String in C? for some more information.
Solution 3:[3]
Note that the storage type of a string in C and C++ is char*
or char[]
. That is, a string in C or C++ is just an array of characters (pointers and arrays in C/C++ are essentially the same).
When you do "ab"+'a'
, "ab" is compiled to a pointer to a fixed string somewhere in memory, and 'a' is compiled to the integer of its ascii value (96). The "ab" is then a pointer to the location of the string in memory, and when you do "ab"+'a', the result is a pointer to the location 96 bytes after the start of your string. The cout
then tries to print whatever data is at that location, which in this case is unprintable.
Solution 4:[4]
you are printing out the arithmetic result of adding memory values of a string and a char.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Baum mit Augen |
Solution 2 | Community |
Solution 3 | zstewart |
Solution 4 | miushock |