凯撒密码 - 出了什么问题?

时间:2014-11-21 13:54:57

标签: c++ string encryption

我遇到启动加密程序的问题。对于单个单词字符串,它运行良好(例如,abcd),但是当我键入两个或三个或更多单词(一个句子,例如,abcd ab ac)时,它不会要求输入密钥,但会重写句子我打字了。我究竟做错了什么?提前致谢。代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>
#include <string>
#include <stdlib.h>
#include <stdio.h>

int main()
{
        int key, l;
        char choose;
        string message;
        cout<<"Type the message"<<endl;
        cin>>message;
        cout<<"Give me a key from 0 to 26"<<endl;
        cin>>key;
        for (int i=0,l=message.size(); i<=l; i++)
        {
            if (isalpha(message[i]))
            {
                if (isupper(message[i]))
                {
                    cout<<(char)('A'+(message[i]-'A'+key)%26);
                }
                if (islower(message[i]))
                {
                    cout<<(char)('a'+(message[i]-'a'+key)%26);
                }
            }
            else
            {
                cout<<message[i];
            }
        }
        return 0;
}

1 个答案:

答案 0 :(得分:1)

使用

std::getline(std::cin, message);

cin 只会读到下一个空格,其余的输入都会保存在流缓冲区中,这样您就可以在第一步中输入您输入的句子的下一个单词作为输入第二个 cin