C++回文字符串判断代码输入lol提示非回文,是什么原因?
代码错误点说明
- 核心错误:for循环起始下标越界。C++
std::string的有效下标范围是0 ~ word.length()-1,你把i初始值设为word.length(),取到的是字符串末尾的空终止符\0,和第一个字符对比必然不相等,直接触发了「不是回文」的输出逻辑。 - 变量未初始化:
int points;定义时没有赋初始值0,累加操作属于未定义行为,最终判断条件points == word.length()结果不可靠。 - 逻辑冗余:发现字符不匹配后没有直接跳出循环,且两个独立的if判断存在重复判断的问题,
is_string变量全程未参与核心判断逻辑,属于无效变量。
修正后的代码
#include <iostream> #include <string> using namespace std; int main() { system("Color 0A"); string word; cout << "write a word and see if it is a palindrome" << endl; cin >> word; bool is_palindrome = true; int len = word.length(); // 只需要遍历前半段字符和后半段对应位置对比即可 for (int i = 0; i < len / 2; i++) { if (word[i] != word[len - 1 - i]) { is_palindrome = false; break; } } if (is_palindrome) { cout << "is a palindrome"; } else { cout << "is not a palindrome"; } return 0; }
内容的提问来源于stack exchange,提问作者João Guilherme
相关产品推荐
相关产品推荐

