Reputation: 115
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.
Upvotes: 2
Views: 7108
Reputation: 11787
cout<<"Enter movie name";
getline(cin, mvName);
Works fine!
Maybe you had to use getline(cin, mvName);
twice was because you inputted some character into the first getline(cin, mvName);
like Space, Enter, etc.
Upvotes: 0
Reputation: 153905
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.
Upvotes: 7
Reputation: 121981
As the question contains no new-line character I suspect you hit enter to move down from the "Enter movie name"
question? This would put a blank line into stdin
, which the first getline()
would read and then second getline()
would read your entered text.
To remove the requirement of typing the initial new-line character just add it to the question's string literal:
std::cout<< "Enter movie name:\n";
Upvotes: 1
Reputation: 24412
Maybe you just forget to add \n
in your prompt message:
cout<<"Enter movie name:\n";
But if you want skip empty lines - do this:
// skip empty lines
while (cin >> mvName && mvName.empty());
// here mvName contains non empty string or it is empty because of error in reading
....
Upvotes: 1
Reputation: 503
I had no issues using:
char mvName[32];
cin.getline(mvName, 32);
And I only had to call it once, again with no issues.
Upvotes: 2