-2

I wrote a program using the getline() function.

code

I think the problem is in this part:

    int encrypt(){
    int opt,limit;
    char inp[100],enc[100];
     cout<<"Choose the encryption type\n"
        <<"[1]Simple\n"
        <<"[2]complex\n"
        <<">>>";
    cin>>opt;
    if(opt==1){
    cout<<"Enter string to be encrypted :";
    cin.getline(inp,100);
    limit=strlen(inp);
    for(int i=0;i<limit;i++)
        {
        switch(inp[i])
                {
                case 'a' :  enc[i]='q';
                            cout<<enc[i];
                            break;

                ..........

It prints enter string to be encrypted and suddenly exits :p

Thanks in advance

Fareanor
  • 3,773
  • 1
  • 4
  • 26
Nived.R.S
  • 17
  • 3
  • 4
    [mcve] please.. – Jesper Juhl Feb 14 '20 at 17:11
  • 7
    1) "_it prints enter string to be encrypted and suddenly exits :p_". How do you know that it exits when it gets to this line? Did you step through your code with a debugger, to verify that? 2) Issue might be related to: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction), but impossible to be certain without [mre]. – Algirdas Preidžius Feb 14 '20 at 17:31

1 Answers1

0

cin.ignore() after the cin>>opt, should do the job(a quickfix). @Algirdas has referred a link that gives you more detail, its because of the newline you get in stream due to input for opt.

int encrypt(){
int opt,limit;
char inp[100],enc[100];
 cout<<"Choose the encryption type\n"
    <<"[1]Simple\n"
    <<"[2]complex\n"
    <<">>>";
cin>>opt;
if(opt==1){
cout<<"Enter string to be encryped :";
cin.ingore() #this can help in clearing the '/n' in stream
cin.getline(inp,100);
limit=strlen(inp);
for(int i=0;i<limit;i++)
    {
    switch(inp[i])
            {
            case 'a' :  enc[i]='q';
                        cout<<enc[i];
                        break;

            ..........

Try it out.

Zarak1
  • 83
  • 10
  • Addendum: consider using `std::string` rather than the `char` arrays. Why this is important: `cin.getline(inp,100);`will not overflow, the 100 makes sure of that (but avoid [magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad)), but if is reads 100 characters without finding a newline the `cin` will be placed in the fail state and become unreadable. This is not checked for or corrected. – user4581301 Feb 14 '20 at 18:41