#include <string>
#include <iostream>
int main()
{
std::string test("hello world ");
std::string label("label test");
test.append(&label[3]); //----- #1
std::cout << test << std::endl;
}
for the above code, what I expected is "hello world e", but in fact, its output is "hello world el test". It append all the characters after position 3 to my string test.
At the position #1, if I don't put the & sign, there will be compilation error:
str_append.cpp:10:10: error: no matching member function for call to 'append'
test.append(label[3]);
~~~~~^~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1516:19: note: candidate function not viable: no known conversion
from 'value_type' (aka 'char') to 'const value_type *' (aka 'const char *') for 1st argument; take the address of the argument with &
basic_string& append(const value_type* __s);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1513:19: note: candidate function not viable: no known conversion
from 'value_type' (aka 'char') to 'const std::__1::basic_string<char>' for 1st argument
basic_string& append(const basic_string& __str);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1525:9: note: candidate function template not viable: requires 2
arguments, but 1 was provided
append(_InputIterator __first, _InputIterator __last);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1532:9: note: candidate function template not viable: requires 2
arguments, but 1 was provided
append(_ForwardIterator __first, _ForwardIterator __last);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1515:19: note: candidate function not viable: requires 2
arguments, but 1 was provided
basic_string& append(const value_type* __s, size_type __n);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1517:19: note: candidate function not viable: requires 2
arguments, but 1 was provided
basic_string& append(size_type __n, value_type __c);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1514:19: note: candidate function not viable: requires at least 2
arguments, but 1 was provided
basic_string& append(const basic_string& __str, size_type __pos, size_type __n=npos);
^
1 error generated.
The only way i can solve this is to change the #1 line to :
test += label[3];
So, I want to know what the logic behind this? Can't label[3] return a single character? why it fails when i just use test.append(label[3]);. And why test += label[3]; succeeds?
Thanks in advance.