trouble writing to files in a loop

c++

Solution

The problem associated with your code is here:

 cin.ignore(numeric_limits<streamsize>::max(), '\n');

will ignore a whole line. then when you try to use `getline` to get the next line, you get nothing inside the while loop.

You can fix this as follows:(EDIT as pointed by Pablo)

do
{
    if (question.length() >0)
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.clear(); 
    cout<<"Enter a question:\n\n";
    getline(cin,question);
    a_file<<question<<"\n";
    cout<<"Would you like to enter another question?\n";
    cout<<"1 for yes. 2 for no: ";
    cin>>x;
}while (x!=2);

I tried this fix will gcc 4.5.3, it worked well as expected. There should exist more elegant fix.

Problem

I'm having problems getting this program work correctly. The program asks for a question and then writes that question to a file. Then it ask you if you want to enter another question. If you hit '1' it will loop and ask you to enter another a question. The program itself runs and closes without any issues. The problem is no matter how many questions I enter, it will only write the first question to file. The rest are replaced by blank lines. If I close the program and rerun it, it will, again, only write one line. I'm certain cin.ignore has something to do with it but I can't figure out how to fix it. Please help. ``` #include <iostream> #include <fstream> #include <limits> #include <string> using namespace std; int main () { string question; int x; ofstream a_file("test.txt",ios::app); do { cout<<"Enter a question:\n\n"; getline(cin,question); a_file<<question<<"\n"; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout<<"Would you like to enter another question?\n"; cout<<"1 for yes. 2 for no: "; cin>>x; } while (x!=2); a_file.close(); cout<<"\nYour submition has been saved. Have a nice day!\n"; cout<<"Press enter to close the program."; cin.ignore(); cin.get(); } ```

Original source