当值不能恒定时如何修复"Expression must have a constant value"?

How to fix "Expression must have a constant value" when the value cannot be constant?

本文关键字:have must constant value Expression 不能 定时 何修复      更新时间:2023-10-16

问题是我的错误输出不断说明"表达式必须具有恒定值"四次。

我已经使用了此站点,并尝试了分配内存并删除它,但对此一无所获。我更改了" mystr.length((;"到一个数字,虽然允许该程序运行,但它提供了无效的结果。

char letter = 'Y';
int position = 0;
string productNames[7] =
{ "Pen", "Paper", "Computer", "Pepsi", "Coke", "Book", "Scanner" };
int prizeOfproducts[7] = { 10, 2, 5000, 50, 45, 400, 2000 };
while (letter == 'Y')
{
    string mystr = "";
    cout << "enter the product name you want to search : ";
    cin >> mystr;
    int n = mystr.length();
    char char_array[n + 1];
    strcpy(char_array, mystr.c_str());
    bool flag = false;
    for (int i = 0; i < 7; i++)
    {
        int m = productNames[i].length();
        char char_arrayOrig[m + 1];
        strcpy(char_arrayOrig, productNames[i].c_str());
        if (strstr(char_arrayOrig, char_array) == NULL)
        {
            flag = false;
        }
        else
        {
            flag = true;
            position = i;
            break;
        }
    }
    if (!flag)
    {
        cout <<
            "entered product not found in the product list . Do you want to search again Y/N ? : ";
        cin >> letter;
    }

我只是希望该程序工作而不是由于错误而停止,但是,我希望结果准确。

无需混合C - 样式std :: String和C-Style Char Arrays。如果要使用动态大小字符串-STD :: String是您所需的。如果您尝试使用char [],并且不知道它的大小 - 您可能不需要C ...

尝试考虑使用char []的地方的std :: string或std ::向量。这是您问题的直接解决方案的示例:

//char char_array[n + 1];
std::vector<char> char_array(n + 1);
相关文章: