C++ cin.getline() causes program to crash

I'm making a simple encryption/decryption program... I'm a beginner.

#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;
}

The first time I use getline() it works flawlessly. However when I try to use it to write in the key[] string, it crashes the program.

Can anyone tell me what's going on?

Upvotes: 2

Views: 2495

Answers (2)

wilx
wilx

Reputation: 18228

Do not use istream::getline(), use std::getline() instead. It is safer.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180500

The problem is that you are mixing your input types. When you call

cin>>f;

That leaves a newline in the input buffer. Then on your call to getline() key only gets the newline. What you need to do is clear the input buffer before you call getline. I like to use:

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

Upvotes: 1

Related Questions