【问题标题】:loop logic, encrypting array C++循环逻辑,加密数组 C++
【发布时间】:2012-04-18 08:53:55
【问题描述】:

我正在尝试对数组执行一些操作,最终目标是进行简单的加密。但无论如何,我的数组长度为 458 个字符,主要由字母和一些逗号、句点等组成。我试图从数组的最后一个字符开始,转到第一个字符并将数组中的所有字母大写。它正确读取了最后一个字符 "",但是 for 循环中的下一步就像是 4 个字符并跳过了几个字母。我的控制逻辑有问题吗?

void EncryptMessage (ofstream& outFile, char charArray[], int length)
{
    int index;
    char upperCased;
    char current;

    for (index = length-1; index <= length; --index)
    {
        if (charArray[index] >= 'A' && charArray[index] <= 'Z')
        {
            upperCased = static_cast<char>(charArray[index]);
            current = upperCased;
            outFile << current;
        }
        else
        {
            charArray[index]++;
            current = charArray[index];
        }

    }
}

【问题讨论】:

    标签: c++ arrays encryption for-loop uppercase


    【解决方案1】:

    if 语句的else 分支中,您设置了current 的值,但从未将其写出,因此写出的所有内容都是以大写字母开头的(以及其他已经指出,您的循环条件不正确)。

    如果我这样做,我的结构会有所不同。我会写一个小函子来加密一个字母:

    struct encrypt { 
        char operator()(char input) { 
            if (isupper(input))
                return input;
            else
                return input+1;
        }
    };
    

    然后我将输入放入std::string,并使用std::transform对其进行操作:

    std::string msg("content of string goes here.");
    
    std::transform(msg.rbegin(), msg.rend(), 
                   std::ostream_iterator<char>(outFile, ""), 
                   encrypt());
    

    【讨论】:

      【解决方案2】:

      变化:

      for (index = length-1; index <= length; --index)
      

      到:

      for (index = length-1; index >= 0; --index)
      

      【讨论】:

      • 这行得通,但我得到了非常奇怪的随机顺序输出,并且没有一个字母是大写的
      • 没关系,问题出在 else 语句中,索引再次不必要地增加了。现在完美运行
      • 您只想将小写字母改为大写字母吗?
      • 不加密也包括减去 asccii 值,但从 else 语句中删除一行并修复循环修复它。谢谢
      猜你喜欢
      • 2011-06-05
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 2012-02-29
      • 1970-01-01
      • 2016-05-17
      相关资源
      最近更新 更多