简体   繁体   中英

C++: Why am I getting an error: “array initializer must be an initializer list or string literal”?

just started with 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 . 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[ ] . 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.

All help is appreciated.

Cheers!

you can not directly assign a string to char array

bool feast(string beast, string dish){

    bool elig;

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

    return elig;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM