I'm trying to write a function within my class that I can call within the program to write questions from the running program to a file. My problem is that when I call getline(...), it doesn't wait for a user input...sometimes. Here's what happens when I run the program: (Input 1, 2, and 3, and Y were inputs by me)
Would you like to enter a question? Y/N:
Y
Please enter the question.
Please enter answer #1
(pause for input)
Input 1
Is this the correct answer? Y/N
(pause for input)
Y
Please enter answer #2
Please enter answer #3
(pause for input)
Input 2
Please enter answer #4
Input 3
Press any key to continue...
The file after this looks like this:
Input 1
Input 2
Input 3
Input 1
(The blanks are intentionally there)
Note, the program I'm using them in just declares a class of that type and calls this function:
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
void trivia::question_to_file()
{
bool corr=false; // Used to ask user which answer is correct
char user_input; // Used to read user choice
string temp, correct_answer; // Used to temporarily store question/answers
ofstream fout;
fout.open("questions.txt");
if(fout.fail())
{
cout << "There was an error opening the output file";
exit(1);
}
cout << "Would you like to enter a question? Y/N:" << endl;
cin >> user_input;
while((toupper(user_input) != 'Y') && (toupper(user_input) != 'N'))
{
cout << "Invalid input. Please enter Y for yes, or N for no" << endl;
cin >> user_input;
}
if(toupper(user_input) == 'N')
{
cout << "Returning to main menu" << endl;
return;
}
if(toupper(user_input) == 'Y')
{
cout << "Please enter the question." << endl;
getline(cin, temp, '\n');
fout << temp << endl;
for(int i=1; i<5; ++i)
{
cout << "Please enter answer #" << i << endl;
getline(cin, temp, '\n');
if(corr == false)
{
cout << "Is this the correct answer? Y/N" << endl;
cin >> user_input;
while(toupper(user_input) != 'Y' && toupper(user_input) != 'N')
{
cout << "Invalid input. Please enter Y for yes, or N for no" << endl;
cin >> user_input;
}
if(toupper(user_input) == 'Y')
{
correct_answer = temp;
corr = true;
}
}
fout << temp << endl;
}
if(corr == false)
{
cout << "No correct answer was chosen. Using answer #4." << endl;
fout << temp << endl;
}
else
{
fout << correct_answer << endl;
}
}
}
|
Any help with why I'm skipping lines would be much appreciated. Thanks!