C++凯撒密码程序执行错误的字符

标签 c++ caesar-cipher

这是我尝试加密“This is a test sentence!”时得到的结果:“Ymnxp����p������t��������”

我之前测试过我的加密部分,它运行良好。

谁能告诉我我做错了什么?

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include "unistd.h"

using namespace std;


void displayUsage(){
    // Displays how to use this program
    // TODO
    cout << "Instruction: \n use -r to give rotation number \n use -f to give file name" <<endl;
}


int main(int argc, char **argv){

  string text;
  char* input_file_name;
  int rotation;
  bool have_rotation = false;
  bool have_input_file_name = false;


    // process command-line arguement
    int opt = 0;
    extern char *optarg;
    static const char* opt_string = "r:f:";
    opt = getopt( argc, argv, opt_string);
    while(opt != -1) // While there are parameters to parse, do so
    {  
        switch(opt)
        {
            case 'r':
                have_rotation = true;
                rotation = atoi(optarg);
                break;
            case 'f':
                have_input_file_name = true;
                input_file_name = optarg;
                break;
            default:
              displayUsage();
              return 1;
        }
        opt = getopt( argc, argv, opt_string);  // Pull the next parameter, or 0 if none.
    }

    if(!have_rotation)
    {
      displayUsage();
      return 0;
    }

    if(have_rotation)
    {
      if(have_input_file_name)
      {     
        ifstream file(input_file_name);
        string text2, temp;
        while(!file.eof())
        {
          getline(file, temp);
          text2 += temp;
          text2 += "\n";
        }
        text = text2[text2.size()-2];
      }
      else
      {
      cout <<"Enter text:"<<endl;
      cin >> text;
     }
    }

    char cipher[text.size()];

    for(int i=0; i<text.size(); i++)
    {
      cipher[i] = text[i];
      if(islower(cipher[i]))
      {
        cipher[i] = (cipher[i] - 'a' + rotation)%26 + 'a';
      }
      else if(isupper(cipher[i]))
      {
        cipher[i] = (cipher[i] - 'A' + rotation)%26 + 'A';
      }
    }

    cout <<cipher<<endl;

  return 0;
}

最佳答案

我猜这个错误是因为你没有用 '\0' 终止你的 cipher 数组。

打印函数将处理数组中的字符(可能超出数组),直到找到“\0”字符。

你的数组应该大一个来说明这个终止字符。

或者摆脱 char 数组并使用 std::string

关于C++凯撒密码程序执行错误的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32288937/

相关文章:

c++ - 施放 ssize_t 或 size_t

c++ - 无法打开已编译的项目

c++ - Win32 C++ 低级键盘钩子(Hook)导致奇怪的行为

c++ - 访问类似单例的静态成员的段错误

c - 在 C 中的 Caesar Cipher 中需要帮助

c++ - 获取 C++ ofstream 的 put 指针的原始值(用于存储)

c - caesar.c 的奇怪输出

Java - AES CBC 算法生成 SecretKeySpec 的不同方式

python - 与凯撒密码的 ASCII 循环作斗争