【问题标题】:C++ Simple EncryptionC++ 简单加密
【发布时间】:2013-04-06 20:43:57
【问题描述】:

我阅读了 Bjarne Stroustrup 的《C++ 编程语言》一书,他的练习之一是进行简单的加密。我输入一些东西,用 std::cin 读取它并加密它+将加密的文本打印到屏幕上。我就是这样做的:

在我的 int main() 中:

std::string read;
std::cin >> read;

encript(read);

我的功能(只是一部分):

void encript(const std::string& r){

std::string new_r;
for(int i = 0; i <= r.length(); i++)
{
    switch(r[i])
    {
        case 'a':
            new_r += "a_";
            break;
        case 'b':
            new_r += "b_";
            break;
        case 'c':
            new_r += "c_";
            break;
        case 'd':
            new_r += "d_";
            break;
... //goes on this way 
    }
}

std::cout << new_r << std::endl;

我现在的问题是我真的必须写下每一个字符吗?我的意思是这些只是非大写字符。还有特殊字符、数字等。

还有其他方法吗?

【问题讨论】:

  • 如果 C++11 没问题,new_r += {r[i], '_'};。这需要一个由字符和下划线组成的初始化列表(想想数组初始化)并将其添加到字符串的末尾。
  • 你可以得到a的数量和计算其他的
  • @Bakudan,除非它们不能保证是连续的。
  • @chris 如果我这样做,每个字符都会变成 '_' ,对吗?那我就不能解密了?
  • 不是你的问题,但这是一个错误for(int i = 0; i &lt;= r.length(); i++)。应该是for(int i = 0; i &lt; r.length(); i++)

标签: c++ encryption character


【解决方案1】:

当然还有另一种方式:

new_r += std::string(1,r[i]) + "_";

【讨论】:

    【解决方案2】:

    如果你使用 range-for,它会更干净:

    std::string new_r;
    for (char c : r) {
        new_r += c;
        new_r += '_';
    }
    

    【讨论】:

      【解决方案3】:

      这将是相同的:

      void encript(const std::string& r){
      
      std::string new_r;
      for(int i = 0; i < r.length(); i++) // change this too
      {
          new_r += r[i];
          new_r += "_";
      }
      
      std::cout << new_r << std::endl;
      

      但或者您可以只使用 STL。不必使用 C++11:

      string sentence = "Something in the way she moves...";
      istringstream iss(sentence);
      ostringstream oss;
      
      copy(istream_iterator<char>(iss),
           istream_iterator<char>(),
           ostream_iterator<char> (oss,"_"));
      
      cout<<oss.str();
      

      输出:

      S_o_m_e_t_h_i_n_g_i_n_t_h_e_w_a_y_s_h_e_m_o_v_e_s_。 _。 _。 _

      【讨论】:

      • += 可以采用单个字符,这与构造函数不同,因此 new_r += r[i]; 有效。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      相关资源
      最近更新 更多