-1

I read some answers regarding how to fix it but I'm trying to also understand the concept behind it (i.e. why does the first getline work fine).

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

int main(){
string ticker = "";
string date = "";
int pprice;
int sprice;

cout << "Enter the stock ticker =>" << endl;
getline(cin, ticker);
cout << "Enter the purchase price =>" << endl;
cin >> pprice;

IT WORKS FINE UNTIL IT GETS TO HERE:

cout << "Enter the sell date =>" << endl; 
getline(cin, date);      
cout << "Enter the sell price =>" << endl;
cin >> sprice;

cout << ticker << endl;

return 0;
}

/*OUTPUT:
Enter the stock ticker =>
XYZ
Enter the purchase price =>
12.34
Enter the sell date =>
Enter the sell price =>
12.34
XYZ
*/
Abdul
  • 11
  • 1
  • 2
  • 3
  • 1
    Possible duplicate of [cin and getline skipping input](http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input) – LogicStuff Apr 24 '16 at 06:52
  • I actually tried that before posting this because cin.ignore(); did not work. It only causes the program to terminate. – Abdul Apr 24 '16 at 07:48
  • You entered a float (12.34) while pprice (and sprice) should be an int. So pprice will be 12 and date .34. – Bob__ Apr 24 '16 at 12:38

1 Answers1

0

You're probably not using cin.ignore() in the correct place. It should be used after std::cin and before getline().

For Example:

int x;
string y;
cin >> x;
cin.ignore(INT_MAX);
getline(cin, y);

The idea is to remove the carriage returns, newlines etc that cin leaves behind on the stream which cause getline() to immediate take and return.

asterx
  • 85
  • 1
  • 8