C++反转字符串无输出且无编译错误,求问题原因排查
问题分析与解决
你的反转字符串函数没有输出,核心问题是循环条件写反了:
原代码里的循环条件是i <= 0,但初始i的值是textword.length() - 1(比如传入"marc"时,i初始为3),3 <= 0不成立,循环根本没执行,所以revWord一直是空字符串,自然没有输出。
把循环条件改成i >= 0就能正常遍历所有字符了,修正后的代码如下:
#include<iostream> std::string reverse_text(std::string textword) { std::string revWord = ""; // 修正循环条件为i >= 0 for(int i = textword.length() - 1; i >= 0; i-- ){ revWord += textword[i]; } return revWord; } int main() { std::cout << reverse_text("marc"); // 现在会输出"cram" }
另外提个小优化:可以提前给revWord分配好空间,避免字符串频繁扩容,效率更高:
std::string revWord(textword.size(), ' '); for(int i = textword.length() - 1, j = 0; i >= 0; i--, j++){ revWord[j] = textword[i]; }
或者直接用C++标准库的std::reverse函数更简洁:
#include<iostream> #include<algorithm> // 需要包含这个头文件 std::string reverse_text(std::string textword) { std::reverse(textword.begin(), textword.end()); return textword; }
内容的提问来源于stack exchange,提问作者hpoly01
相关产品推荐
相关产品推荐

