C ++, Incorrect conversion from 'char to' const char *

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 get 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 do I go from char to const char* ? Can I insert a character at position 0 of a string?

+8
c ++ string pointers
source share
4 answers

The error message tells you everything you need to know - you are trying to pass a char parameter where const char * is required.

You just need to change:

 expression_input.insert(0,'('); expression_input.append(')'); 

in

 expression_input.insert(0,"("); expression_input.append(")"); 
+10
source share

There is no std::string::insert that takes only position and character. You want insert(0, 1, '(') , which inserts 1 character at position 0.

The same goes for std::string::append : append(1, ')')

+4
source share

Now I don’t understand why the compiler says that I am converting from char to const char *.

The reason you get a compilation error is because there is no corresponding overload for the set of arguments that you pass to the method. The compiler tries to find the closest match, which in your case is char and const char* , and then reports this error.

Please help me.

There are 8 overloads for std :: string :: insert and 6 overloads for std :: string :: append . You have many different options, for example:

 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 are many possibilities, just choose the one that you find the most readable or accessible for your situation.

+3
source share

The version of the string :: insert function used requires that const char * you put in char use "instead

Here is a link to the method documentation

http://www.cplusplus.com/reference/string/string/insert/

0
source share

All Articles