The sstream wouldn't read twice..!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  int a =0;
  string mystr;
  float price=0;
  int quantity=0;
do{
  cout << "Enter price: ";
  getline (cin,mystr);
  stringstream(mystr) >> price;
  cout << "Enter quantity: ";
  getline (cin,mystr);
  stringstream(mystr) >> quantity;
  cout << "Total price: " << price*quantity << endl;
  cin>>a;
  }

while (a==2);

cout<<"done";
return(0);
}


Hello all,
In this code, at the second run, the program does not prompt for "price" input..!!
Wonder why that is so..?
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  int a =0;
  string mystr;
  float price=0;
  int quantity=0;
do{
  cout << "Enter price: ";
  getline (cin,mystr);
  stringstream(mystr) >> price;
  cout << "Enter quantity: ";
  getline (cin,mystr);
  stringstream(mystr) >> quantity;
  cout << "Total price: " << price*quantity << endl;
  cout << "Enter 2 to continue "; // <--
  cin>>a;
  cin.ignore(1000,'\n'); // <--
  }

while (a==2);

cout<<"done";
return(0);
}
Thanks,
What was happening..?
and what does "cin.ignore" do.?
closed account (48T7M4Gy)
Check it out in the reference section on this site.

But the idea is if you go from cin to getline at any time you need to clear (in this case by ignoring everything up to '\n' )the stream because there might be extra characters in the stream left over after the cin 'grabs' enough to supply your variable a. What is leftover after that is 'grabbed' by the next input instruction, in this case getline, and that messes things up.
Last edited on
Thank you..!!
Topic archived. No new replies allowed.