【发布时间】:2020-12-15 08:00:26
【问题描述】:
我正在编写一个程序来反转字符串并在其间插入随机字符。 这是我的代码: main.cpp
#include <iostream>
#include <chrono>
#include <thread>
#include "encrypter.cpp"
using namespace std;
int main(int argc, char *argv[])
{
char message[256];
this_thread::sleep_for(chrono::milliseconds(1000));
cout << "Make sure theres no one around you" << endl;
this_thread::sleep_for(chrono::milliseconds(1000));
cout << "Enter secret message ";
cin.get(message, 256);
cout << "message encrypted" << endl;
enc(message);
return 0;
}
加密器.cpp
#include <iostream>
#include <string>
int getRandom(int a, int b) {
return a + (rand() % static_cast<int>(b - a + 1));
}
using namespace std;
void enc(char message[256]) {
int i = 0;
int len = strlen(message);
int revlen = len - 1;
int wtpselector;
int charselector;
int encsim;
char randchar[6] = "@#$%&";
char strreved[256];
char strenc[1024];
while (i < len) {
strreved[revlen] = message[i];
i++;
revlen--;
}
revlen = strlen(strreved);
len = revlen - 1;
i = 0;
encsim = 0;
while (i < revlen) {
wtpselector = getRandom(0, 4);
charselector = getRandom(0, 4);
if (wtpselector == 0) {
strenc[encsim] = strreved[i];
i++;
encsim++;
} else {
strenc[encsim] = randchar[charselector];
encsim++;
}
}
cout << strenc << endl;
}
但输出中有许多不应该存在且不在程序中的随机字符。 喜欢:
Input: hello world
Output: $%@$#&&d&&@%$%1%row &#$$@%&ol@%#@%&1%&#$&#ehe$%%€@@8@&%@$#& #%@@%&¢&@%#&#$#@$#%%##&%#@&#&$8%#$#@#$@$@#%&&@&#@Q#$$#&¢%@% Q#\#&$@#{&&&&$@¢ \ $$$$@@@@@#&&&%%&&%{ $@¢v#&@&~u@@@@%&%¢
请帮忙!!!
【问题讨论】:
-
您有什么理由不使用
std::string而不是char 数组吗?它会让事情变得更简单。 -
您似乎忘记了 C++ 中的
char字符串实际上称为 null-tterminated 字节字符串。 -
因为这是一个关于char数组的学习项目。