This is probably a very simple problem but forgive me as I am new.
Here is my code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string name;
int i;
string mystr;
float price = 0;
cout << "Hello World!" << endl;
cout << "What is your name? ";
cin >> name;
cout << "Hello " << name << endl;
cout << "How old are you? ";
cin >> i;
cout << "Wow " << i << endl;
cout << "How much is that jacket? ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << price << endl;
system("pause");
return 0;
}
The problem is that when asked how much is that jacket? getline does not ask the user for input and just inputs the initial value of “0”. Why is this?
You have to be careful when mixing
operator>>withgetline. The problem is, when you useoperator>>, the user enters their data, then presses the enter key, which puts a newline character into the input buffer. Sinceoperator>>is whitespace delimited, the newline character is not put into the variable, and it stays in the input buffer. Then, when you callgetline, a newline character is the only thing it’s looking for. Since that’s the first thing in the buffer, it finds what it’s looking for right away, and never needs to prompt the user.Fix:
If you’re going to call
getlineafter you useoperator>>, call ignore in between, or do something else to get rid of that newline character, perhaps a dummy call togetline.Another option, and this is along the lines of what Martin was talking about, is to not use
operator>>at all, and only usegetline, then convert your strings to whatever datatype you need. This has a side effect of making your code more safe and robust. I would first write a function like this:You can create a similar function for floats, doubles and other things. Then when you need in int, instead of this:
You do this: