Two programs; accepts inputs; then outputs

I am currently writing two programs for school that do the following.

Part A: Write a program to open a text file named "CSC2134N.TXT" for output, then accept an integer from the console and a float value from the console (in separate input operations) and write the numbers to the file. An integer value of 0 should be used as a code value to cause the program to quit accepting numbers from the console and close the file.

Here is an example of how the input should be done:
Enter an integer (0 to quit): 34
Enter a float value: 2.37
Enter an integer (0 to quit): 127
Enter a float value: -42.7
Enter an integer (0 to quit): 0
(program ends)

Part B: I then need to write another program to open the text file named "CSC2134N.TXT" that I created in Part A for input, and read all the numbers from the file and display them on the screen. It must read an integer value from the file, and then a float value. It cannot simply read the lines as character data. Assume that the integer and float; values exist as pairs in the file.


This is what I have for Part A

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

using namespace std;

int main()

{
int intVal;
float floatVal;

ofstream file1;  //declare the file variable
file1.open("CSC2134N.TXT");  //open the file for output

if (!file1)
    {
    cout << "error opening CSC2134.TXT" << endl;
    return 0;
    }

while (intVal != 0)
    {
    cout << "Enter an integer (0 to quit) ";
    cin >> intVal;
    if (intVal != 0)
        {
        file1 << intVal << endl;
        cout << "Enter a float value: ";
        cin >> floatVal;
        file1 << floatVal << endl;
        }
    else  file1.close();  //close file;
    }
}




And this is what I have for Part B

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
int i;
float j;

ifstream file1;  //declare the file variable
file1.open("CSC2134N.TXT");  //open the file for output

while(!file1.eof()) // loop until the end of the file is reached
   {
      file1 >> i >> j;
      cout << i << ", " << j << endl;
   }

   file1.close();    //   close file1
   return 0;
}



Anyways the code runs it just duplicates the last input from Part A in the output from Part B twice. Any suggestions? or hints please?
Last edited on
I am just not sure if my last input from Part A is becoming duplicated, or if Part B is just reading the last output twice?
Topic archived. No new replies allowed.