Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must type getline(cin, string) twice?

need your help in getting user inputs.
I want users to type a string that has spaces. i cant use cin>>variable as the space in between makes the problem go wrongly. if i use getline(cin,string_variable) it works correctly. but i need to type twice in order to make it work proberly.

cout<<"Enter movie name";
getline(cin, mvName);
getline(cin, mvName);

Is there a better way to get user input than this or is there any other codes to type rather than typing the getline twice? Pls advice.

like image 200
rasul1719435 Avatar asked Jul 20 '26 08:07

rasul1719435


2 Answers

When switching between formatted input using in >> value and unformatted input, e.g., using std::getline(in, value) you need to make sure that you have consumed any whitespace you are not interest in. In you case there is probably a newline in the buffer from a prior input. Assuming you are nit interested in leading whitespace the easiest approach is to use something like this:

if (std::getline(std::cin >> std::ws, mvName)) {
    process(mvName);
}

BTW, you should always check that your input was successful.

like image 78
Dietmar Kühl Avatar answered Jul 22 '26 00:07

Dietmar Kühl


I had no issues using:

char mvName[32];

cin.getline(mvName, 32);

And I only had to call it once, again with no issues.

like image 25
M4rc Avatar answered Jul 21 '26 23:07

M4rc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!