我正在尝试使用递归函数按字母顺序打印字符串,但它给出了字符串下标超出范围的错误。
string alpha(string word)
{
char temp;
int count = 0;
int i = 0;
while (count < word.size())
{
if (word[i] > word[i + 1])
{
temp = word[i];
word[i] = word[i + 1];
word[i + 1] = temp;
i++;
if (i >= word.size())
{
alpha(word);
}
}
else
{
count++;
}
}
return word;
}
最佳答案
因为你使用 if (word[i] > word[i + 1])
你必须在结束之前停止你的循环......并且你需要 count
或 i
(不是两者);也就是
while (i + 1 < word.size()) // <-- like so
或者你可以使用
int i = 1;
while (i < word.size()) {
if (word[i - 1] > word[i]) {
关于c++ - 按字母顺序排列的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25451470/