Just started working with strings, what's wrong with this program?

When I try to enter input it won't let me enter anything for string m2 or string m3. What's weird is when I simply rearrange the code it works fine. What is wrong with this format such that it won't let me enter all needed input values?



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

int main()
{
double a1, a2, a3, average;
string m1, m2, m3;

cout << "Enter the name of the first month: ";
getline(cin, m1);
cout << "\nEnter the inches of rainfall in " << m1 <<": \n";
cin >> a1;

cout << "Enter the name of the second month: ";
getline(cin, m2);
cout << "\nEnter the inches of rainfall in " << m2 << ": \n";
cin >> a2;

cout << "Enter the name of the third month: ";
getline(cin, m3);
cout << "\nEnter the inches of rainfall in " << m3 << ": \n";
cin >> a3;

average = (a1 + a2 + a3) / 3;
cout << "The average rainfall for " << m1 << ", " << m2 << ", and " << m3 << " is " << average << "inches." << endl;

system("Pause");
return 0;
}



Example output with bold input:

Enter the name of the first month: June

Enter the inches of rainfall in June:
10
Enter the name of the second month:
Enter the inches of rainfall in :
12
Enter the name of the third month:
Enter the inches of rainfall in :
11
the average rainfall for June, , and is 11inches.
Last edited on
after a statement like this cin >> a1; there is a newline in the input stream from the user pressing enter. Then when getline executes the first character it sees is the newline which is the delimiter that getline uses so nothing happens. try adding ignore statements to remove the extra newline.

1
2
cin >> a1;
cin.ignore();
Last edited on
Thanks! So pressing Enter causes a newline character('\n') to be stored in the keyboard buffer, thereby causing causing my problems.
Topic archived. No new replies allowed.