Absolute C++ beginner - Problems with cin/cout

Hi programmers
I've been a Java man until now, which will likely explain the problems I've been having. I've written the following code, which is basically just a Caesar Cipher:

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
void decrypt()
{
    prompt();
    for(int index = 0; index < text.length(); index++)
    {
        text[index] -= key;
    }
    cout << text << endl;
}

void encrypt()
{
    prompt();
    for(int index = 0; index < text.length(); index++)
    {
        text[index] += key;
    }
    cout << text << endl;
}

void prompt()
{
    cout << "Enter the text:  ";
    getline(cin, text);
    cout << "\nEnter the key:  ";
    string keyString;
    cin >> keyString;
    stringstream(keyString) >> key;
}


There's a main function that has a menu system also, but it seems to work correctly. My problem is that when I use either the encrypt() or decrypt() functions, the output from the prompt function doesn't wait for me to enter anything after printing "enter the text" before it prints "enter the key". Then once I've entered something the encrypt/decrypt function ends without outputting anything, and returns to the menu. I've tried to follow the tutorials on this site, but I'm not getting the same results.
Can anyone help? I realise this is really simple but I'm stuck.

[EDIT] Forgot to mention, there're also global fields for "text" (a string) and "key" (an int).
Last edited on
Yes, this is a common problem when mixing getline and the >> operator to get input. getline doesn't leave the newline character, '\n', (which is generated when you hit enter) in the input buffer. The >> operator does. What happens is that your getline function, when called, "sees" the '\n' left in the buffer from the previous input operation and assumes you've entered nothing and hit enter. Fix it by using only getline to get your data, or by adding a cin.get(); (or a while(cin.get()!='\n');) statement after every use of the >> operator.
Very detailed explanation, thank you. Turned out it was to do with my menu after all, as it was its >> operator causing the trouble.
Thanks again.
Topic archived. No new replies allowed.