gpt4 book ai didi

c++ - 无法从函数返回动态字符串

转载 作者:行者123 更新时间:2023-11-30 05:39:42 25 4
gpt4 key购买 nike

我在 reddit 上写了一些关于加密字符串的代码挑战,我想到了这样的事情:

#include <iostream>
#include <string>

using namespace std;

string encrypt(string sentence);

int main()
{
string sentence;
int i = 0;
cout << "Welcome. Enter a sentence: ";
getline(cin, sentence);
cout << sentence << endl;
encrypt(sentence);
cout << endl << endl;
system("pause");
return 0;
}

string encrypt(string sentence)
{

int i = 0;
int x = (sentence.size());
string *encrypted_sentence = new string[sentence.size()];
int *wsk = new int[sentence.size()];
for (i = 0; i < x; i++)
{
wsk[i] = sentence[i];
}

for (i = 0; i < x; i++)
{
if (wsk[i] == ' ')
continue;
else if (islower(wsk[i]))
{
if (wsk[i] <= 99)
wsk[i] = (wsk[i] + 23);
else
wsk[i] = (wsk[i] - 3);
}
else
{
if (wsk[i] <= 67)
wsk[i] = (wsk[i] + 23);
else
wsk[i] = (wsk[i] - 3);
}
}
for (i = 0; i < x; i++)
{
//cout << static_cast <char> (wsk[i]);
encrypted_sentence[i] = wsk[i];
}

return *encrypted_sentence;
}

我的问题是,没有返回任何内容。运行程序后,我什么也得不到。有人能用这个给我指出正确的方向吗?我错过了什么?

最佳答案

第一个 main() 返回一个 int alwaysvoid main() 不是标准的。其次:

string encrypted_sentence = new string[sentence.size()];

甚至不会编译。 encrypted_sentencestd::string 类型,但您试图为其分配一个 std::string *。第三you should avoid using using namespace std;

更新:

我相信您正试图在以下位置输出加密字符串:

cout << endl << endl;

但这一切所做的只是输出 2 个换行符并将输出刷新两次。如果要显示加密的字符串,则需要捕获 encrypt() 函数的返回值并显示它,或者 encrypt() 可以通过引用获取字符串.如果您更改 encrypt() 以获取引用,那么它将变为:

void encrypt(string & sentence)
{
string *encrypted_sentence = new string[sentence.size()]; // get rid of this line as it is not needed.
//...
for (i = 0; i < x; i++)
{
sentence[i] = wsk[i];
}
}

然后你将输出字符串:

cout << sentence << endl;

关于c++ - 无法从函数返回动态字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32206377/

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