Reputation: 31
Hey guys I have a question about storing the output to a variable. Let's say I have 3 variables defined as follows:
float num,
string units,
string rest;
and the user enters this in the console:
12.2
mg
Vitamin
I know if I want to store it in variables, I have to do the following:
cin >> num >> units >> rest;
But let's say the user enters Vitamin A instead of Vitamin.
And the I want to store the rest of the string after mg into 'rest' variable. how do I do that?
I did the following:
cin >> num >> units;
getline(cin,rest); //stores the rest of the string into rest
But this also stores the space character after mg
namely if I output rest
, it would output " Vitamin A"
. I don't want this space in the beginning. How do I accomplish this?
I know it's long but I hope I made it clear. Any help or suggestions would be helpful. Thanks,
Upvotes: 0
Views: 78
Reputation: 23634
You can skip whitespace by using std::ws
cin >> num >> units;
ws(cin);
getline(cin, rest);
You can see a live working example here: ignore leading whitespace
Upvotes: 3