Input/Output using .txt files

I need to write a file that:

a. Prompts the user for the name of an output file in which to store some integers.
b. Opens a file with that name.
c. Prompts the user to enter a list of positive integers terminated by a -1. As the user enters a number, the program saves the number (including the -1) to the file.
d. Closes the output file.

Second half:

a. Reopens the file as an input file.
b. Checks to see if the file exists. If not, the program should exit.
c. Reads the integers from the file and echoes them to the screen until the -1 is read. The program should not echo the -1.
d. Closes the stream.

I test it with the values 1, 2, 3, 4, 5, and -1.

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
  #include <iostream>
#include <fstream>
int main()
{
    using namespace std;
    ifstream inp;
    ofstream outp;
    char fileName[81];
    int input;
    //------------------
    cout << "Make a file name below: \n";
    cin >> fileName;
    //------------------
    outp.open(fileName);//open file under outp
    while(outp.fail())//if the file fails
    {
        outp.close();
        outp.clear();
        cout << "Error Re-Enter: \n";
        cin >> fileName;
        outp.open(fileName);}
    //------------------
    cout << "Make values for the file (enter a -1 to end): ";
    cin >> input;
    while(input != -1)//loop until end command '-1' is input
    {
        outp << input << " ";
        cin >> input;}
    outp.close();
    //------------------    
    inp.open(fileName);//open file under inp
    while(inp.fail())//if the file fails
    {
        inp.close();
        inp.clear();
        cout << "File does not exist.\n";
        exit(1);}
    //------------------
    int values;
    inp >> values;
    cout << values;
    
    system("pause");
    inp.close();
    return 0;
}


I have looked up how to echo the values of the file that I make, but always end up with the wrong output. Any help would be appreciated. Thanks.
ifstream objects have the extraction operator overloaded so just the same way you read values using cin, you can use the ifstream object to do the same:

1
2
3
4
5
6
inp >> values;
while (values != -1)
{
    cout << values << " ";
    inp >> values;
}


For the above to work, you have to have a -1 in your file, but with the way you have created your while loop on line 25, a -1 will never be stored in the file, so you have to fix that
@Smac89 Thanks, I forgot about that part! But I still have the problem of outputting the values in the program. I still need that part cleared up for me.
Topic archived. No new replies allowed.