【问题标题】:Random and replacement characters in c++ outputc++ 输出中的随机字符和替换字符
【发布时间】: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数组的学习项目。

标签: c++ arrays string random


【解决方案1】:

你错过了两件重要的事情:

  • 当您声明一个数组时,它的值未定义(无论内存中的内容)
  • strlen 计入“\0”字符的第一次出现

为了让您的代码正常工作,您必须初始化 char 数组,这意味着更改这两行:

char strreved[256];
char strenc[1024];

到:

char strreved[256] = {0};
char strenc[1024] = {0};

【讨论】:

  • 有空格和没有空格有什么区别?这也会修复随机字符错误吗?
  • 空间与它无关,只是风格问题(我修复了它)。
猜你喜欢
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2021-06-12
相关资源
最近更新 更多