Weird function call issue

I've been trying to get back into learning c++ again. I'm having trouble with this. When I run this, everybody works except that when I select 1 for encryption, it only does the cout statements then exits. If I comment everything else out and just call encrypt () in main, the function works perfectly. I don't get it. Is this not correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  #include <iostream>
#include <string>

using namespace std;

void encrypt();
void decrypt();

int main()
{
    int choice;
    cout << "\tCaesar Cipher" << endl
    << "1. Encrypt" << endl
    << "2. Decrypt" << endl
    << "Select: ";
    cin >> choice;
    
    if(choice == 1)
    {
        encrypt();
    }
    else if(choice == 2)
    {
        decrypt();
    }
    else
    {
        cout<<"Error, bad input, quitting\n";
    }
}

void encrypt()
{
    string inString;
    int length;
   
    cout << "Enter text to encrypt: ";
    getline(cin, inString);
    length = inString.length();
    for(int i = 0; i<length; i++)
    {
        if(isalpha(inString[i]))
        {
            inString[i] = tolower(inString[i]);
            for(int j=0; j<7; j++)
            {
                if(inString[i] == 'z')
                {
                    inString[i] = 'a';
                }
                else
                {
                    inString[i]++;
                }
            }
        }
    }
    cout << "Code is: " << inString;
}

void decrypt()
{
    cout << "Under construction.";
}
You're using cin >> choice, which reads an integer.
Your input is an integer and a RETURN.
After cin >> choice, there's a RETURN in the input buffer.
getline reads till RETURN.
You get nothing :)

How to solve: call getline after cin, and then call encrypt.

Last edited on
How do I do that? I've tried getline (cin, choice) and cin.getline () and both error out.
After every formatted input(cin >> x), call cin.ignore(), to remove the trailing newline feed.
Thank you both for the help! Cin.ignore () worked. Thank you!
Topic archived. No new replies allowed.