C ++ cin.getline()导致程序崩溃

时间:2014-12-15 18:49:21

标签: c++ cin

我正在制作一个简单的加密/解密程序......我是初学者。

#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <string>

using namespace std;

char s[1025];
char o[1025];
char key[1025];

char tochar(int a)
{
    if(a<26) return 'a'+a;
    if(a>25 and a<52) return 'A'+a-26;
    if(a>51) return '0'+a-52;
}
int toint(char t)
{
    if(t>='a' and t<='z') return 0-'a'+t;
    if(t>='A' and t<='Z') return 26+t-'A';
    if(t>='0' and t<='9') return 52+t-'0';
}

int main()
{
    int i,j,keylenght;
    //for(j=0;j<62;j++)cout<<j<<" "<<tochar(j)<<" "<<toint(tochar(j))<<endl;
    cout<<"Enter String:\n";
    cin.getline(s,1024);
    cout<<"Function [encrypt/decrypt]: ";
    char f;
    cin>>f;
    if(f=='e')
    {
        cout<<"Generate key? [y/n]: ";
        cin>>f;
        if(f=='y')
        {
            cout<<"Enter key length [up to 1024]: ";
            cin>>keylenght;
            srand(time(0));
            for(i=0;i<keylenght;i++)
            {
                key[i]=tochar(rand()%62);
            }
        }
        else
        {
            cout<<"Enter key: \n";
            cin.getline(key,1024);
            for(keylenght=0;key[keylenght]!='\0';keylenght++);
        }

        for(i=0;s[i]!='\0';i++)
        {
            if(key[keylenght%i]!=' ')
            {
                if(s[i]!=' ')o[i]=tochar((toint(s[i])+toint(key[i%keylenght]))%62);
                else o[i]=' ';
            }
            else
            {
                o[i]=s[i];
            }
        }
        cout<<endl<<"Encrypted string: "<<o<<endl<<"Generated key: "<<key;
    }
    else
    {
        cout<<"Enter key: ";
        cin>>key;
        for(keylenght=0;key[keylenght]!='\0';keylenght++);
        for(i=0;s[i]!='\0';i++)
        {
           if(s[i]!=' ')
           {
               if(key) o[i]=tochar((62+toint(s[i])-toint(key[i%keylenght]))%62);
           }
           else o[i]=' ';
        }
        cout<<endl<<"Decrypted string:\n"<<o;
    }
    return 0;
}

我第一次使用getline()时它完美无瑕。但是,当我尝试使用它来写入key []字符串时,它会使程序崩溃。

谁能告诉我发生了什么?

2 个答案:

答案 0 :(得分:1)

问题是您正在混合输入类型。当你打电话

cin>>f;

在输入缓冲区中留下换行符。然后在您调用getline()键时只获取换行符。您需要做的是在调用getline之前清除输入缓冲区。我喜欢用:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

答案 1 :(得分:0)

请勿使用istream::getline(),而是使用std::getline()。它更安全。

相关问题