Palindrome程序帮助c ++

时间:2015-01-07 23:29:27

标签: c++

我在回文程序中翻转字符串时遇到了麻烦。我想要的是输入“cat”,然后输出“tac”,但是当我运行它时,它不会显示反转的字符串,程序停止工作。任何人都可以帮助我吗?

#include <iostream>
#include <string.h>

using namespace std;

int main(){
string phrase1,phrase2;
int len;

cout<<"Please enter a word or phrase: ";
cin>>phrase1;
len = phrase1.length();

for(int a=1;a<=len;a++){
    phrase2[len-a] = phrase1[a-1];
}
cout<<endl<<phrase1<<endl<<phrase2<<endl;

return 0;
}

2 个答案:

答案 0 :(得分:3)

您需要先将短语2调整到合适的长度。

phrase2.resize(len);

答案 1 :(得分:2)

当你这样写:

for(int a=1;a<=len;a++){
    phrase2[len-a] = phrase1[a-1];
}

你试图用phrase1的反向填充phrase2。但是你从来没有为phrase2分配内存!

由于这是一个回文,你知道你希望phrase2具有相同大小的phrase1,所以你可以预先写phrase2.resize(len);

相关问题