Reputation: 23
Trying to run this:
// appending to string
#include <iostream>
#include <string>
int
main()
{
std::string str;
std::string str2 = "Writing ";
std::string str3 = "print 10 and then 5 more";
// used in the same order as described above:
str.append(str2); // "Writing "
str.append(str3, 6, 3); // "10 "
str.append("dots are cool", 5); // "dots "
str.append("here: "); // "here: "
str.append(10u, '.'); // ".........."
str.append(str3.begin() + 8, str3.end()); // " and then 5 more"
str.append<int>(5, 0x2E); // "....."
std::cout << str << '\n';
return 0;
}
But having error on str.append(5,0x2E):
error: no matching function for call to ‘std::__cxx11::basic_string::append(int, int)’
Using VS Code 1.43.1, running on ubuntu 19.10, gcc version 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2).
I've tried to run the code on Code::Blocks 16.01 IDE, and windows, but had same error.
Upvotes: -1
Views: 9731
Reputation: 882316
There is no variant of std::string::append()
that takes two integers - you should make the second parameter a character, as there is a variant that takes an integer and a character.
In addition, by using <int>
, you change the templated character type charT
into an integer rather than a character, which is probably not going to work the way you expect. A std::string
is generally defined as std::basic_string<char>
so appending with .append<int>
is going to have weird effects on the underlying memory at best.
Since you're wanting to add five more .
characters, I'm not sure why you wouldn't just do:
str.append(5, '.');
Upvotes: 0
Reputation: 29985
You just don't need the <int>
part. str.append(5, 0x2E);
compiles fine.
Upvotes: 0
Reputation: 330
When having problems with the standard template library, you can always take a look at the c++ reference of the function you're using: http://www.cplusplus.com/reference/string/string/append/
In this case, there isn't any reason to specify the after your append: When doing this, both arguments get interpreted as an int, while you want the second to be interpreted as a char. You can simply achieve this by doing str.append(5,0x2E);
. Your compiler will search the closest matching function, which is string& append (size_t n, char c);
and implicitly convert the second argument to a char.
Upvotes: 0
Reputation: 44
You need to convert 0x2E
(integer) to char: char(0x2E)
first.
str.append<int>(5,char(0x2E));
Upvotes: 0