读书人

看看这个程序有什么不妥没?该怎么解决

发布时间: 2012-03-20 14:01:11 作者: rapoo

看看这个程序有什么不妥没?
题目::::称正读和反读都相同的字符序列为“回文”,例如,“abcddcba”、“qwerewq”是回文,“ashgash”不是回文。试写一个算法判断读入的一个以“@”为结束符的字符序列是否为回文。

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
string s;
string sum;
cout < < "请输入一个字符串(以符号‘&’结束): " < <endl;
while(cin> > s) //while用于把输入的字符串储存到string sum中。
{
sum+=s;
if(sum.size()==1&&sum[0]== '& ') //这里的判断当只输入一个字符‘&’ 时,重新输入
{
cout < < "必须在 '& '输入字符串,请重新输入: " < <endl;
sum= " ";
continue;
}
if(s[s.size()-1]== '& ') //用于检测字符串后面的‘&’检测到停止读入字符串。
break;
}
//for语句用于判断是不是回文字符串
for(string::size_type begin=0,end=(sum.size()-2);begin!=end&&begin!=end+1;++begin,--end)
{
if(sum[begin]!=sum[end])
{
cout < < "您所输入的不是回文字符串! " < <endl;
return 0;
}
}
cout < < "您所输入的是一个回文字符串! " < <endl;

return 0;
}


[解决办法]
我觉得挺好的. 我照你这个也写了个, 不过for不变式的处理跟你有点小区别.

// test5.cpp
// cl -EHsc test5.cpp

#include <iostream>
#include <string>
#include <cstdlib> // for std::size_t
#include <cassert> // for assert
#include <cmath> // for std::floor

bool is_same(std::string const & s) {
assert(!s.empty());
std::size_t length = s.size() - 1; // 不算&
assert(s[length] == '& ');
std::size_t half = std::floor(static_cast <double> (length));

for(std::size_t offset = 0; offset != half; ++offset)
if(s[offset] != s[length - offset - 1]) return false;

return true;
}

int main() {
std::string input;
while(std::cin > > input) {
if(is_same(input))
std::cout < < "您所输入的是一个回文字符串! " < < std::endl;
else
std::cout < < "您所输入的不是回文字符串! " < < std::endl;
}
return EXIT_SUCCESS;
}

读书人网 >C++

热点推荐