[英]C++: Why am I getting an error: “array initializer must be an initializer list or string literal”?
just started with C++. 刚开始使用C ++。 Was playing around with arrays and strings and encountered the error: "array initializer must be an initializer list or string literal". 在处理数组和字符串时遇到错误:“数组初始化器必须是初始化器列表或字符串文字”。 Here is my code: 这是我的代码:
#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;
}
What I want to do is check if the first char of the beast string is equal to the last char of the dish string then output true , else false . 我想做的是检查野兽字符串的第一个字符是否等于菜式字符串的最后一个字符 ,然后输出true ,否则输出false 。 So I am converting the beast string to an array of chars and then checking for their first element, for both beast and dish . 所以我将野兽字符串转换为字符数组,然后检查野兽和盘的第一个元素。
But I keep encountering this error. 但是我一直遇到这个错误。
Error corresponds to char beastM[ ] and char dishM[ ] . 错误对应于char beastM []和char dishM [] 。 To my knowledge, this code should work since both beast and dish are given as strings in the function parameters. 据我所知,该代码应该起作用,因为在函数参数中, 野兽和菜肴都以字符串形式给出。 And converting them to a char array shouldn't be much of a problem. 并将它们转换为char数组不是什么大问题。
All help is appreciated. 感谢所有帮助。
Cheers! 干杯!
you can not directly assign a string to char array 您不能直接将字符串分配给char数组
bool feast(string beast, string dish){
bool elig;
elig = (beast.at(0) == dish.at(dish.length() - 1) ? true : false;
return elig;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.