添加额外输出语句时,代码会产生意外输出

时间:2015-11-14 01:16:33

标签: c++

所以我正在测试一个赋值的某些参数,它基本上使用提供的密码加密文本文件。这是代码,它没有像我期望的那样工作:

int main()
{
fstream file("text.txt",ios::out, ios::trunc);
ifstream key("key.txt");
char box[16][2];
string input;
getline(cin, input);
file << input;

for (int row = 0; row < 16; row++)
{
    for (int col = 0; col < 2; col++)
    {
        key >> box[row][col];

    }
}

for (int i = 0; i < input.length(); i++)
{
    for (int row = 0; row < 16; row++)
    {
        if (input.at(i) != box[row][0])
        {
            cout << input.at(i);
        }
        else if (input.at(i) == box[row][0])
        {
            input.at(i) = box[row][1];
            cout << input.at(i);
        }
    }
}

file.close();
key.close();

system("pause");
}

但如果我将i循环替换为:

for (int i = 0; i < input.length(); i++)
{
    for (int row = 0; row < 16; row++)
    {
        if (input.at(i) == box[row][0])
        {
            input.at(i) = box[row][1];
            cout << input.at(i);
        }
    }
}

它可以正常工作,但它不会读取不在密码文件中的任何内容。这包括空格和一切。所以我想,好吧,让我们添加一些代码,当我以前的条件不满足时,它会做一些事情。那...... produces unexpected output.。仅供参考,here is the output of the original code使用相同的单词。

1 个答案:

答案 0 :(得分:0)

使用修改后的逻辑,您将打印每个字符16次。如果可以找到它的密码,你仍然可以再打印15次。

相关问题