我正在写一些关于加密字符串的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;
}
我的问题是,没有任何东西可以归还。在我运行程序后,我得不到任何回报。有人能指出我正确的方向吗?我错过了什么?
答案 0 :(得分:2)
首先main()
会返回int
始终。 void main()
不标准。其次:
string encrypted_sentence = new string[sentence.size()];
甚至不会编译。 encrypted_sentence
类型为std::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;
答案 1 :(得分:0)
如果有人想要回答这个问题,我会想出这个问题,我很确定它最终会按照我想要的方式运作:
#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;
}
答案 2 :(得分:-1)
代码显然是错误的。 string * encrypted_sentence = new string [sentence.size()];分配ARRAY字符串!不是一个字符串。从这一点来看,你可以看到你的代码是错误的。