Reputation:
In C++ I have this program:
#include <iostream>
using namespace std;
int main(){
string expression_input;
cout << "User Input: " << endl;
getline(cin, expression_input);
expression_input.insert(0, '('); //error happens here.
expression_input.append(')');
}
I am getting the following error:
prog.cpp:15: error: invalid conversion from ‘char’ to ‘const char*’
prog.cpp:15: error: initializing argument 2 of
‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT,
_Traits, _Alloc>::insert(typename _Alloc::rebind<_CharT>::other::size_type,
const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>,
_Alloc = std::allocator<char>]’
Where am I am converting from char
to const char*
? Can't I insert a character at position 0 of a string?
Upvotes: 9
Views: 31973
Reputation: 474476
There is no std::string::insert
that takes only a position and a character. What you want is insert(0, 1, '(')
, which inserts 1 character at position 0.
The same goes for std::string::append
: append(1, ')')
Upvotes: 5
Reputation: 20332
Now I don't get why does the compiler says I am converting from char to const char*.
The reason you are getting a compilation error is because there is no matching overload for the set of arguments you are passing to the method. The compiler tries to find the closest match, which in your case char
and const char*
, and then reports that error.
Please help me out.
There are 8 overloads for std::string::insert and 6 overloads for std::string::append. You have many different options such as:
expression_input.insert(0, "(");
expression_input.append(")");
or
expression_input.insert(expression_input.begin(), '(');
expression_input.append(")");
or even
expression_input.insert(0, 1, '(');
expression_input.append(")");
There's many possibilities, just choose one that you find most readable or sutiable for your situation.
Upvotes: 3
Reputation: 706
the version of string::insert function you are using requires const char* you are putting in char use " instead of '
here is a link to method documentation
http://www.cplusplus.com/reference/string/string/insert/
Upvotes: 0
Reputation: 213210
The error message tells you everything you need to know - you're trying to pass a char
parameter where a const char *
is required.
You just need to change:
expression_input.insert(0,'(');
expression_input.append(')');
to:
expression_input.insert(0,"(");
expression_input.append(")");
Upvotes: 11