Program closes with cin.get ()

closed account (y6DLy60M)
I wrote this program to calculate the rain fall average of 3 months. You are asked what month and then amount of rain that fell within that month.
For some reason it takes the information but before it calculates it or shows me anything it closes.
Help?




//Average Rain fall
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
char month1[30], month2[30], month3[30];
long double rain1, rain2, rain3, averageRain;



cout<< "What is the name of the first month? ";
cin>> month1;


cout<< "How many inches of rain fell in "<< month1;
cout<<"? ";
cin>> rain1;


cout<< "What is the name of the second month? ";
cin>> month2;

cout<< "How many inches of rain fell in " << month2 ;
cout<< "? ";
cin>> rain2;


cout<< "What is the name of the third month? ";
cin>> month3;

cout<< "How many inches of rain fell in " <<month3 ;
cout<< "? ";
cin>> rain3;

averageRain = (rain1 + rain2 + rain3)/(3);

cout<< "The average rainfall for "; month1; ","; month2; ", and"; month3; "is";
averageRain = (rain1 + rain2 + rain3)/(3);
cout<< averageRain;
cout<< "inches.";
cin.get ();
return 0;
}
cin.get(); reads one character from cin. If there is no character to read it will wait until there is.

In your case there is a new line character still in cin so cin.get(); will read that character and return right away.
put cin.sync(); right before cin.get();
closed account (y6DLy60M)
Thanks peter for clarifying that. tntxtnt cin.sync works. thanks
Could you mark this as solved?

std::cin.get() will extract the last character left in the input buffer, which should be a newline character. You'll have to add, like suggested before, std::cin.sync() or std::cin.ignore() in front of std::cin.get() to solve this problem.
Last edited on
Topic archived. No new replies allowed.