Requirement: Correct the following program so that it will write the same number
ID: 3553813 • Letter: R
Question
Requirement: Correct the following program so that it will write the same numbers to a file as well as, optionally, display the numbers on the screen.
The original program is as follows:
#include <QtCore/QCoreApplication>
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
srand(time(NULL));
int num;
ofstream theWave;
ifstream inputStream;
theWave.open("com4:");
for(int i = 0; i < 10; i++)
{
num = rand() % 1000;
cout<<num<<endl;
theWave<<num<<endl;
}
theWave.close();
inputStream.open("junk2.dat");
if(inputStream.fail())
{
inputStream.clear();
cout<<"That file does not exist!!!"<<endl;
inputStream.close();
exit(0);
}
int count = 0;
while(inputStream >> num)
cout<<"just read item "<<count++<<": "<<num<<endl;
inputStream.close();
cout<<"The end!"<<endl;
return a.exec();
}
Explanation / Answer
// additionally added code is in bold
#include <QtCore/QCoreApplication>
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
srand(time(NULL));
int num;
ofstream theWave;
ifstream inputStream;
theWave.open("com4:");
for(int i = 0; i < 10; i++)
{
num = rand() % 1000;
cout<<num<<endl;
theWave<<num<<endl;
}
theWave.close();
inputStream.open("junk2.dat");
theWave.open("out.dat");
if(inputStream.fail())
{
inputStream.clear();
cout<<"That file does not exist!!!"<<endl;
inputStream.close();
exit(0);
}
int count = 0;
while(inputStream >> num){
cout<<"just read item "<<count++<<": "<<num<<endl;
theWave<<"just read item "<<count++<<": "<<num<<endl;
}
inputStream.close();
cout<<"The end!"<<endl;
theWave<<"The end!"<<endl;
theWave.close();
return a.exec();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.