gpt4 book ai didi

c++ - 反向字符串脚本给出运行时错误

转载 作者:行者123 更新时间:2023-11-30 01:56:14 25 4
gpt4 key购买 nike

我已尽力修复我的逻辑,但我无法检测到错误。我不能使用 [] 或任何其他高级功能,因为我还没有介绍它们。如果可以,请告诉我我的错误。请不要给我负分,因为我已经尽力了,我的错误没有意义!谢谢。

这个脚本应该反转输入字符串:例如:hi 到 ih。

#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;

void ReverseString(string &aString);

int main(){
string info;
cout << "What's your string?" << endl;
getline(cin, info);
cout << info << " compare with: " << endl;
ReverseString(info);
cout << info << endl;
system("pause");
return 0;
}

void ReverseString(string &aString)
{

for(int i = 0; i < aString.length(); i++)
{

int u = aString.length() - 1 - i;
string temp = "";
temp += aString.at(aString.length() - 1 - i);
if(u == 0 )/* when aString.length() - 1 - i == 0, the last char will have been processed*/
{
aString = temp; /*store temp into aString; when its value changes, it is passed into info's value*/
}


}

}

最佳答案

您的问题是,每次您在 ReverseString() 中运行 for 循环时,您都会重新初始化您的 temp 变量,删除您已经拥有的所有内容保存在字符串中。如果我对 ReverseString 函数执行此操作,您的程序将按预期运行:

void ReverseString(string &aString)
string temp = "";

for(int i = 0; i < aString.length(); i++)
{

int u = aString.length() - 1 - i;
temp += aString.at(aString.length() - 1 - i);
if(u == 0 )/* when aString.length() - 1 - i == 0, the last char will have been processed*/
{
aString = temp; /*store temp into aString; when its value changes, it is passed into info's value*/
}

关于c++ - 反向字符串脚本给出运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19937543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com