Convert the following C program to C++.
More instructions follow the code.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int main(int argc, char *argv[]) {
int numerator = 25;
int denominator = 10;
int i = 0;
/*
You can assume the files opened correctly and
the
correct number of of command-line arguments were
entered.
*/
FILE * inPut = fopen(argv[1],
"r");
FILE * outPut = fopen(argv[2],
"w");
float result =
(float)numerator/denominator;
fprintf(outPut,"Result is %.2f\n",
result);
float arr[SIZE];
for( ; i < SIZE; i++) {
fscanf(inPut, "%f",
&arr[i]);
fprintf(outPut, "%7.4f\n",
arr[i]);
}
return 0;
}
Notice this is uses command-line arguments. I have provided an input file called num.txt that will be used when running the program. The output file is called out.txt.
Make sure you are using C++ style file I/O (FILE pointers/fopen) as well as regular I/O including the C++ style output formatting (fscanf, fprintf, formatting). Also use the C++ method of casting. The lines above that are bold are the lines that you need to convert to C++. Don't forget to add the necessary C++ statements that precede the main() function.
Below is the given code in C++:
#include<iostream>
#include<fstream>
#include<iomanip>
#define SIZE 5
using namespace std;
int main(int argc, char
*argv[])
{
int numerator = 25;
int denominator = 10;
int i = 0;
// open a file in read mode.
ifstream inPut;
inPut.open(argv[1]);
// open a file in write
mode.
ofstream outPut;
outPut.open(argv[2]);
float result =
(float)numerator/denominator;
outfile<<fixed<<setprecision(2)<<"Result is
"<<result<<endl;
float arr[SIZE];
for( ; i < SIZE; i++) {
infile >> arr[i];
outfile<<fixed<<setprecision(4)<<arr[i]<<endl;
}
return 0;
}
Most of the syntax is same, just that of file handling is different.
NOTE: Install stream library if it is not present.
Get Answers For Free
Most questions answered within 1 hours.