Unable to input in cin when using sstream

closed account (ybRX92yv)
There is no error code, that's the problem, when I use the code below.
Everything worked fine until I added the code that is between the @@@@@@@@@@

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
cout << "Hello World" << endl;
int a=5, b=20, c, d, e, f, age;
cout << "20-5=";
cout << b-a << endl;
string mystr;
string mystr2;
cout << "Hi, what's your first name?" << endl;
getline (cin, mystr);
cout << "Hi " << mystr << ", what a nice name!" << endl;
cout << "How old are you?" << endl;
cin >> age;
c=age*365;
d=c*24;
e=d*60;
f=e*60;
cout << "You have lived about:" << endl << age << " years." << endl << c << " days." << endl << d << " hours." << endl << e << " minutes." << endl << f << " seconds." << endl;
int i;
cout << "Enter a number: ";
cin >> i;
cout << "The number you entered is " << i << " and it's double is " << i*2 << endl << endl;

@@@@@@@@@@
float price=0;
int quantity=0;
cout << "Enter price: ";
getline (cin,mystr2);
stringstream(mystr2) >> price;
cout << "Enter quantity: ";
getline (cin,mystr2);
stringstream(mystr2) >> quantity;
cout << "Total price: " << price*quantity <<
endl;
@@@@@@@@@@
system("pause");
return 0;
}



The code on itself works, tested in a seperate project using only that code, but when including it in this code the output is that when asking for the price and quantity I see:
Price:Quantity:
Then I can only input something after the quantity, meaning that the result (price) is always 0 as I just can't input to price.

Anyone knows what I'm doing wrong?

This is a test program, I know there are different ways to do this but just this on itself isn't working and I'm trying for hours..
Last edited on
This is a common problem. cin >> i only reads the characters it needs. This means that it leaves the newline char in the stream. This newline is them picked up by getline and an empty line is read. All you need to do is add cin.ignore() after cin >> i.
Topic archived. No new replies allowed.