.txt file not saving inputs

I am trying to write up a code that ask a user for how many numbers will be inputted. Then take that many numbers and save them to a .txt file and repeat, saving the next set of numbers in the next line of the .txt file, until a user inputs -1. The code will compile and run fine the problem is that it will only save the first set of numbers from the user. Can anybody tell me what is causing 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    int size;
    ofstream outputFile;
    
    cout << "How many numbers will be inputted (Enter -1 to stop)?" << endl;
    cin >> size;
    double array [size];
    
    do{
	cout << "Enter the numbers to be saved in the file: ";
	for (int i=0; i<size; i++)
	{
	    cin >> array [i];
	}
    
	outputFile.open ("output.txt");
	for (int i=0; i<size; i++)
	{
            outputFile << array [i];
	    if ((i+1)<size)
	    {
		outputFile<< ",";
	    }
	}
	
	outputFile << endl;
	cout << "Numbers saved to disk."<<endl;
 
	cout << "How many numbers will be inputted (Enter -1 to quit)?" << endl;
	cin >> size;
    }
    while (size>0);
    outputFile.close();  
}
Open the output file outside of the do loop. When you open it multiple times you reset the stream pointer back to the start, so you are overwriting the previous values.

This works for me:

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
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    int size;
    ofstream outputFile;
    
    cout << "How many numbers will be inputted (Enter -1 to stop)?" << endl;
    cin >> size;
    double array [size];
    outputFile.open ("output.txt");
    do{
	cout << "Enter the numbers to be saved in the file: ";
	for (int i=0; i<size; i++)
	{
	    cin >> array [i];
	}
	for (int i=0; i<size; i++)
	{
            outputFile << array [i];
	    if ((i+1)<size)
	    {
		outputFile<< ",";
	    }
	}
	
	outputFile << endl;
	cout << "Numbers saved to disk."<<endl;
 
	cout << "How many numbers will be inputted (Enter -1 to quit)?" << endl;
	cin >> size;
    }
    while (size>0);
    outputFile.close();  
}
Oh ok that makes sense. Thank You
Topic archived. No new replies allowed.