Need pointers on how to write to a file

Hi! I am having issues with the text file overwriting the last input from the first time it runs.

Let's say that I have three students with three different student IDs and grades. I need the input to be put into the text file and go down to a new line.

When I run this code, it just overwrites the old data with new data without creating a new line instead. May I have a few pointers on what I am doing wrong?

This is just a snippet of the code and if you need more, please let me know!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 cout << "Please enter the Student ID: ";
		cin >> studentID;
	for (int i = 1; i <= 5; i++ )
	{
		cout <<"Quiz 1: ";
		cin >> Quiz1;
		cout << endl;
		i += i;
		cout <<"Quiz 2: ";
		cin >> Quiz2;
		cout << endl;
		i += i;
		cout <<"Quiz 3: ";
		cin >> Quiz3;
		cout << endl;
		i += i;
		cout <<"Quiz 4: ";
		cin >> Quiz4;
		cout << endl;
		i += i;
		
		grading_List.open("Grading_List.txt");
		grading_List << studentID << " " << Quiz1 << " " << Quiz2 << " " << Quiz3 << " " << Quiz4 << endl;
	}


EDIT: I forgot to mention that this loop is also being looped depending or not if the user wants to run the for loop again. I would need to run it three times in this case.
Last edited on
Line 3: What's the purpose of the for loop? You're going to ask for quiz1-quiz4 5 times (ignoring the next problem), but studentID never changes.

Lines 8,12,16,20: Why are you adding i to itself? This is modifying your loop variable. Not a good idea.

Lines 22-23: You're going to be attempting to open "grading_list.txt" 5 times (assuming you fix the previous problem with i) and write the latest values to it.

I'm thinking you want something more like this:
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
    int num_students;
    
    cout << "How many students? ";
    cin >> num_students;
	grading_List.open("Grading_List.txt");
     
	for (int i = 1; i <= num_students; i++ )
	{   cout << "Please enter the Student ID: ";
		cin >> studentID;
		
		cout <<"Quiz 1: ";
		cin >> Quiz1;
		cout << endl;
		cout <<"Quiz 2: ";
		cin >> Quiz2;
		cout << endl;
		cout <<"Quiz 3: ";
		cin >> Quiz3;
		cout << endl;
		cout <<"Quiz 4: ";
		cin >> Quiz4;
		cout << endl;
		
		grading_List << studentID << " " << Quiz1 << " " << Quiz2 << " " << Quiz3 << " " << Quiz4 << endl;
	}


Last edited on
I think I understand! Thanks for the tips!

I need to think more logically on what the for loop will do when code is in that specific loop!

Changing to solved.
Topic archived. No new replies allowed.