[英]Can't return dynamic string from a function
我在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
。 void main()
不是標准的。 其次:
string encrypted_sentence = new string[sentence.size()];
甚至不會編譯。 encrypted_sentence
的類型為std::string
但是您嘗試為其分配一個std::string *
。 第三, 您應該避免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;
萬一有人想找到這個問題的答案,我想出了這個,我很確定它終於可以按照我的意願工作了:
#include <iostream>
#include <string>
std::string encrypt(std::string to_encrypt);
int main()
{
std::string sentence;
std::string result;
std::cout << "Welcome. Please enter a sentence: ";
getline(std::cin, sentence);
result = encrypt(sentence);
std::cout << "Result: " << result << std::endl;
system("pause");
return 0;
}
std::string encrypt(std::string to_encrypt)
{
int i = 0;
int x = (to_encrypt.size());
std::cout << std::endl << "x = " << x << std::endl;
int *temp = new int[to_encrypt.size()];
for (i = 0; i < x; i++)
{
temp[i] = to_encrypt[i];
}
for (i=0; i < x; i++)
{
if (temp[i] == ' ')
continue;
else if (islower(temp[i]))
{
if (temp[i] <= 99)
temp[i] = temp[i] + 23;
else
temp[i] = temp[i] - 3;
}
else
{
if (temp[i] <= 67)
temp[i] = temp[i] + 23;
else
temp[i] = temp[i] - 3;
}
}
std::string encrypted;
for (i = 0; i < x; i++)
{
encrypted += (static_cast <char> (temp[i]));
}
return encrypted;
}
該代碼顯然是錯誤的。 字符串* encrypted_sentence =新字符串[sentence.size()]; 分配字符串數組! 沒有一個字符串。 從中可以看出,您的代碼是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.