【问题标题】:C++: Why am I getting an error: "array initializer must be an initializer list or string literal"?C++:为什么会出现错误:“数组初始值设定项必须是初始值设定项列表或字符串文字”?
【发布时间】:2018-09-13 10:02:37
【问题描述】:

刚开始使用 C++。正在玩数组和字符串并遇到错误:“数组初始化程序必须是初始化程序列表或字符串文字”。这是我的代码:

#include<string>
using namespace std;

bool feast(string beast, string dish){
    int dishLn = dish.length();
    bool elig;
    char beastM[] = beast;
    char dishM[] = dish;

    elig = (beastM[0] == dishM[dishLn - 1]) ? true : false;

    return elig;
}

我要做的是检查 beast string 的第一个 char 是否等于 的最后一个 char菜串然后输出true,否则false。所以我将 beast 字符串 转换为 chars 数组,然后检查它们的第一个元素,beastdish。

但我一直遇到这个错误。

错误对应于 char beastM[ ]char discM[ ]。据我所知,这段代码应该可以工作,因为 beastdish 在函数参数中都是作为字符串给出的。将它们转换为 char 数组应该不是什么大问题。

感谢所有帮助。

干杯!

【问题讨论】:

  • 不工作。出现了一个新错误:'cannot initialize a variable of type of 'char' with an rvalue of type 'const value_type *' (aka 'const char *')'
  • 您声明了两个名为beastMdishM 的未指定大小的char 数组,并尝试使用std::string 类型的对象初始化它们中的每一个。你到底希望那里发生什么?您认为您需要beastMdishM 到底是为了什么?为什么不直接访问字符串beastdish!?

标签: c++ arrays string casting


【解决方案1】:

您不能直接将字符串分配给 char 数组

bool feast(string beast, string dish){

    bool elig;

    elig = (beast.at(0) == dish.at(dish.length() - 1) ? true : false;

    return elig;
}

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 2019-04-16
    • 2021-10-29
    • 2011-01-03
    • 2020-02-23
    • 2010-10-03
    • 2015-09-20
    • 2016-01-22
    • 1970-01-01
    相关资源
    最近更新 更多