C++错误,我不断收到此错误可变大小的对象"OldWord"可能无法初始化
C ++ error I keep getting this error variable-sized object `OldWord' may not be initialized
#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::vector
和std::array
(或std::tr1::array
或boost::array
)。
用20代替word。
值需要复制到OldWord中
尝试改变:
char OldWord[word.length] = word;
char OldWord[20]; // you mentioned 20...
strcpy(OldWord, word.c_str());
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 模板,函数使用错误的构造函数来复制我的对象
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- 错误:malloc:对象 0x7f9edf504080 的 *** 错误:未分配正在释放的指针
- 从对象C++中的文件读取内容时出现分段错误
- cout 新创建的对象引发运行时错误
- 错误:"释放后使用包装器对象 (WRAPPER_ESCAPE)"
- 使用返回对象的函数处理错误
- 创建 QtChart 对象会在运行时创建EXC_BAD_ACCESS错误
- 错误:无法传递非平凡类型"std::string"的对象和更多错误
- 该对象具有与成员函数不兼容的类型限定符.为什么会出现此错误?
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 尝试将对象插入空指针数组时出现分段错误
- 错误:三元运算符无法在对象中正常工作"cout"
- C++:如果括号为空,为什么不抛出错误对象?
- qt vsaddin错误对象引用未设置为对象的istanse
- 如何从函数返回成功或错误对象?
- 复制构造函数错误:对象的类型限定符与成员函数不兼容
- 如何在本机插件中创建node.js错误对象