In: Computer Science
Exercise 2:
3.0 2.1 1.5 1.1 2.6 4.1 |
The first column is voltage and the second column is the electric current.
Write program that reads the voltages and currents then calculates the electric power (P) based on the equation:
Voltage Current Power 3.0 2.1 (result) 1.5 1.1 (result) 2.6 4.1 (result) |
P = v * i
Write your output to the file results.txt with voltage in the first, current in the second and power on the third column.
Your output file should look like
// part a #include #include using namespace std; int main () { ifstream aaa; aaa.open ("circuit.txt"); ofstream ppp; ppp.open("result.txt"); int i; double a,b,p; ppp<< "Voltage"<<" Current"<<" Power"<<endl; for (i=1; i<=3; i++) { aaa>>a>>b; p=b*a; ppp << a <<" "<" "<< p<<endl; } return 0; } |
If you do not know the number of lines in the circuit.dat file in part a, modify your program to read the input file by using eof function.
#include
#include
#include
using namespace std;
int main()
{
ifstream aaa;
aaa.open ("circuit.txt");
ofstream ppp;
ppp.open("result.txt");
// checking if input file is good to open
if(!aaa.is_open())
{
cout << "Error in opening file circuit.txt! Exiting..\n";
exit(EXIT_FAILURE);
}
// checking if output file is good to open
if(!ppp.is_open())
{
cout << "Error in opening file result.txt! Exiting..\n";
exit(EXIT_FAILURE);
}
ppp << "Voltage" << " Current" << " Power" << endl;
double a,b,p;
while(!aaa.eof())
{
aaa >> a >> b;
p = a * b;
ppp << a << " " << b << " " << p << endl;
}
return 0;
}
OUTPUT FILE (result.txt)