ifstream/ofstream troubleshooting

I'm attempting to create a program that reads in 5 lines of text from a text file and then outputs those lines of text, plus the number squared and cubed into another text file.

My code so far looks 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
26
27
28
29
30
31
32
33
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;

void main ()
{ifstream instream;
instream.open ("input.txt");

if(instream.fail())
{cout<<"File was unrecognized"<<endl;}
else
{
int num;
int sq;
int cu;
while (!instream.eof())
{
instream>>num;
sq=num*num;
cu=num*num*num;

}
cout<<num<<"     "<<sq<<"     "<<cu<<endl;

ofstream outstream;
outstream.open("output.txt");
sq= num*num;
cu= sq*num;
outstream<<num, sq, cu;
outstream.close();

}}

What happens is that in the compiler the last number of the file, that number squared, and cubed will be printed, but the rest of the numbers are ignored. The output to the other file only includes the last number.

I have a feeling the problem is in my loop, but I'm relatively new to programming and am not sure where to start to fix the issue.

Thanks!
Last edited on
you overwrite sq and cu with every read line, so at the end only the last one is left

if you have some problems with your code and you have an idea where the error could be, set a breakpoint and debug your code. check the variables and see if they change in each step as they should. mostly you can find the problem that way in a few minutes


and next time use code tags in your post
Last edited on
Your while loop reads the entire file.
After reading the last value, you start to generate the output.

That could work - if you stored all the input values in an array (or vector). As it is, you only have the last number to do anything with.

A straightforward approach would be to open both the input and output files at the start. Then, immediately after successfully reading in a number, calculate and output the results to the output file.

Also, this will attempt to do something after end of file.
1
2
3
4
5
6
while (!instream.eof())
{
    instream>>num;
    sq=num*num;
    cu=num*num*num;
}

A standard approach is this (though there are other ways)
1
2
3
4
5
6
7
instream>>num;
while (!instream.eof())
{
    sq=num*num;
    cu=num*num*num;
    instream>>num;
}

Last edited on
Topic archived. No new replies allowed.