#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 forward\n";
开发者_StackOverflow中文版 cout << "Enter in a word";
cin >> word;
char OldWord[word.length] = word;
cout << OldWord[2];
return 0;
}
If I put 20 in place of word.length, I get "invalid initializer" for error
Well, arrays are neither copyable nor assignable; you have to copy them in a loop, element by element (or use a function that does that for you). In addition, the length of a local array variable must be a compile-time constant; you can't set it at runtime.
Also, std::string
is not an array; why do you think that this assignment would work?
std::string
does allow array-like access, though, so you can use word[2]
, assuming there are at least three characters in the string. In general, raw arrays should be avoided in C++; there are much better options, like std::string
, std::vector
, and std::array
(or std::tr1::array
or boost::array
).
Leave it with 20 instead of word.length and use strcpy to initialize.
The value needs to be copied into OldWord.
Try changing:
char OldWord[word.length] = word;
to
char OldWord[20]; // you mentioned 20...
strcpy(OldWord, word.c_str());
精彩评论