The code skips getline() !!!

closed account (21vXjE8b)
Hey guys! I don't know if here is the right place for my question. Sorry if it isn't!
Yesterday I started working in an encrypting machine. It worked fine, BUT I got a problem. In the place you have to put the message to be codified, if I let getline() the code ignores that line! It skips! If I use cin it works, but I can only put one word.

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
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main(){
	
	string msgToEncrypt, msgToDecrypt;
	char option, c;
	int i, a, b, key_value;
	
	start:
	cout << "CHOOSE AN OPTION:" << endl;
	cout << "A - ENCRYPT A MESSAGE." << endl;
	cout << "B - DECRYPT A MESSAGE." << endl;
	cout << "C - DO NOTHING." << endl;
	cin >> option;
	
	if (option == 'A', 'a') goto encrypt;
	if (option == 'B', 'b') goto decrypt;
	if (option == 'C', 'c') goto end;
	else {
		cout << "INVALID COMMAND." << endl;
		goto start;
	}
	
	encrypt:
	system ("cls");
	cout << "WRITE YOUR MESSAGE:" << endl;
	getline (cin, msgToEncrypt);                        //HERE IS THE PROBLEM!!! 


Maybe the problem is simple, but I started studying C++ a few weeks ago... :(
Last edited on
closed account (48T7M4Gy)
.
Last edited on
closed account (21vXjE8b)
Oh! Thanks for the warning! But... Why it keeps skipping the line?
Last edited on
At line 17
 
    cin >> option;

the user will press the enter key after typing the value of option. That keystroke remains stored in the input buffer as a newline character '\n'.

Later, when the execution reaches line 30,
 
    getline (cin, msgToEncrypt);

the program will read from the input buffer until it reaches the newline '\n'. Thus it reads an empty string and the user doesn't get any chance to type anything.

The solution is after the cin >> option, remove the unwanted trailing newline.
A usual solution is to add an ignore() statement, for example
 
    cin.ignore(1000, '\n');
after line 17. Another possibility is to change line 17 to
 
    cin >> option >> ws;

Note the ws, that tells the program to read and skip any whitespace after the option. Whitespace includes ordinary spaces, tab characters and newlines.
closed account (21vXjE8b)
Thank you Chervil! It worked!
Topic archived. No new replies allowed.