Help me out with this code please!
Hey guys, the problem I'm having here is that the cin.getline statement won't work the second time the loop reaches it.
There are 3 loops, and when the parent loop (the first one) loops a second time, it just skips right past the cin.get and doesn't pause for input! Why does it do this? I hope someone can help!
PS: It does work the first time!
Code:
//--Variable-Declarations-----------------------------------
char Name[3][9] = {" "}; //--01--
int Grades[3][5][6] = {0}; //--02--
string Categories[5] = {"Test Grade",
"Homework Grade",
"Quiz Grade",
"Lab Grade",
"Final Exam Grade"}; //--03--
int MAX[5] = {3, 5, 3, 6, 1}; //--04--
//----------------------------------------------------------
//--Input-Data--------------------------------
for(int i = 0; i != 3; i++) {
cout << "Please input the name for student " << i + 1 << ": ";
cin.getline(Name[i], 9);
for(int ii = 0; ii != 5; ii++) {
for(int iii = 0; iii != MAX[ii]; iii++) {
cout << '\t' << Name[i] << "::" << Categories[ii]
<< ' ' << iii + 1 << ": ";
cin >> Grades[i][ii][iii];
}
cout << '\n';
}
cout << '\n';
}
Re: Help me out with this code please!
Code:
//--Variable-Declarations-----------------------------------
char Name[3][9] = {" "}; //--01--
int Grades[3][5][6] = {0}; //--02--
string Categories[5] = {"Test Grade",
"Homework Grade",
"Quiz Grade",
"Lab Grade",
"Final Exam Grade"}; //--03--
int MAX[5] = {3, 5, 3, 6, 1}; //--04--
//----------------------------------------------------------
//--Input-Data--------------------------------
for(int i = 0; i != 3; i++) {
cout << "Please input the name for student " << i + 1 << ": ";
cin.getline(Name[i], 9);
for(int ii = 0; ii != 5; ii++) {
for(int iii = 0; iii != MAX[ii]; iii++) {
cout << '\t' << Name[i] << "::" << Categories[ii]
<< ' ' << iii + 1 << ": ";
cin >> Grades[i][ii][iii];
cin.ignore(); // Added!
}
cout << '\n';
}
cout << '\n';
}
The reason you need to add that, is that when you get an int from cin, the '\n' character after the number is left in the input buffer. This will cause unexpected behaviour when you start inputting text again. It works the first time since there is no '\n' in the buffer when the application starts.