C++错误,我不断收到此错误可变大小的对象"OldWord"可能无法初始化

C ++ error I keep getting this error variable-sized object `OldWord' may not be initialized

本文关键字:错误 对象 OldWord 初始化 C++      更新时间:2023-10-16
#include<iostream>
#include<cctype> 
#include<string>
#include<cstdlib>
#include"Palindrome.h"
using namespace std;
int main()
{
        Stack S1;
        string word;
        cout << "Do you know what a Palindrome is?n";
        cout << "It is a word that is the same spelling backwards and forwardn";
        cout << "Enter in a word";
        cin  >> word;
        char OldWord[word.length] = word;
                cout << OldWord[2];
        return 0;
}

如果我把20放在word的位置。长度,我得到"无效初始化"错误

数组既不可复制也不可赋值;你必须在循环中一个元素一个元素地复制它们(或者使用一个函数为你做这件事)。此外,局部数组变量的长度必须是编译时常数;你不能在运行时设置。

同样,std::string不是数组;你为什么认为这个任务行得通?

但是

std::string允许类似数组的访问,因此您可以使用word[2],假设字符串中至少有三个字符。一般来说,c++中应该避免使用原始数组;有更好的选择,如std::string, std::vectorstd::array(或std::tr1::arrayboost::array)。

用20代替word。

值需要复制到OldWord中

尝试改变:

char OldWord[word.length] = word;

char OldWord[20]; // you mentioned 20...
strcpy(OldWord, word.c_str());