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.
#include "stdafx.h"
#include <iostream>
#include <fstream>
usingnamespace 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.
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
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;
}