Adding onto a .txt file

So I have to make a program where I give some math questions and the user answers them. The user's answers are stored into an empty .txt file and if they are correct or not in the .txt file. It also needs to display the amount correct.

I just need help adding the stuff into the .txt file

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{
    string Problems[10] = {"12*15", "15*32", "22*30", "50*7", "45*11", "25*30", "25*12", "20*50", "60*30", "15*45"};
    int CorrectAnswers[10] = {180, 480, 660, 350, 495, 750, 300, 1000, 1800, 675};
    int UserAnswer = 0;
    int Score = 0;
    ofstream Quiz;
    
    Quiz.open("MathQuiz.txt", ios::app);
    cout << "Welcome to the math quiz!" << endl << endl;
    
    for(int x = 0; x < 10; x++)
    {
            cout << Problems[x] << " = ";
            cin >> UserAnswer;
            
            if(UserAnswer == CorrectAnswers[x])
            {
                          Score = Score + 1;
                          cout << "Correct" << endl;
            }
            else
                          cout << "Incorrect" << endl;
                          
    cout << "Your score is: " << Score << " out of 10." << endl << endl;
    }
    
    Quiz.close();
    
    system("PAUSE");
    return 0;
}
refer here: http://www.cplusplus.com/doc/tutorial/files/

the easiest way (IMHO) to think about file I/O is that instead of writing (output-ting) to the console you're writing to a file i.e
1
2
3
4
5
6
7
8
9
10
11
// using namespace std etc...

       ofstream fout("myfile.txt", ios::out);

       // now you want to display hello, world in a console
       cout << "Hello, world!" << endl; 

       // write hello, world in a file
       fout << "Hello, world!" << endl;

// note the similarities? 

try to start thinking of ostream and ofstream as objects which we can do stuffs with
Topic archived. No new replies allowed.