找不到错误"invalid conversion from char to const char*"的解决方案



我已经环顾四周,但找不到我的问题的答案。该程序应该在标题上放置星星(*)的边界,但我遇到了错误:

invalid conversion from 'char' to 'const char*' [-fpermissive]

以及错误

initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' [-fpermissive]|
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Please enter your name: " << endl;
string name;
cin >> name;
//Build the message that we intend to write
const string greeting = "Hello " + name + "!";
//Build the second and fourth line of the output
const string spaces = (greeting.size(), ' ');
const string second = "* " + spaces + " *";
//Build the first and fifth lines of the output
const string first = "* " + spaces + " *";
//Write all the output
cout << endl;
cout << first << endl;
cout << second << endl;
cout << "* " << greeting << " *" << endl;
cout << second << endl;
cout << first << endl;
return 0;
}

这是打印出标题周围边框的代码^^(与第一个错误有关)。

// TBD: DPG annotate
template<typename _CharT, typename _Traits, typename _Alloc>
*Error ->* basic_string<_CharT, _Traits, _Alloc>::
basic_string(const _CharT* __s, const _Alloc& __a)
: _M_dataplus(_S_construct(__s, __s ? __s + traits_type::length(__s) :
               __s + npos, __a), __a)
{ }

是与第二个错误有关的代码^^(在字符串函数中)。

我放了两个代码,因为我不知道是由哪个代码。

this:

const string spaces = (greeting.size(), ' ');

应该是

const string spaces(greeting.size(), ' ');

使用=,它试图以表达式(greeting.size(), ' ')的结果初始化spaces。该表达式使用 comma运算符,该操作员评估和丢弃greeting.size(),并给出' '的结果;因此,这相当于

const string spaces = ' ';

尝试使用单个字符初始化string,如果没有合适的构造函数可以这样做。

删除=,它是使用两个构造函数初始化的,给出了一个包含请求的空格数的字符串。

最新更新