Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void ReadData(ifstream& inFile, string name, string type, int n, int v, int Ri[20]);
void ResistanceParallel(int v, int I, int Ri[20]);
void ResistanceSeries(int v, int I, int Ri[20]);
void printData(string name, string type, int n, int v, int Ri[20], float I);
int main()
{
ifstream inFile;
string name;
string type;
int n; //number of components
int v; //voltage of the circuit
int Ri[20]; //number of resistances
int I; //current in the circuit
inFile.open("circuits.dat");
cout << "This is the program to calculate the resistances" << endl;
cout << "Please select the circuit type (series or parallel): ";
cin >> type;
if (type == "series")
{
ReadData(inFile, name, type, n, v, Ri);
ResistanceSeries(v, I, Ri);
printData(name, type, n, v, Ri, I);
}
else if (type == "parallel")
{
ReadData(inFile, name, type, n, v, Ri);
ResistanceParallel(v, I, Ri);
printData(name, type, n, v, Ri, I);
}
inFile.close();
return 0;
}
void ReadData(ifstream& inFile, string name, string type, int n, int v, int Ri[20])
{
inFile >> name >> type;
inFile >> n >> v;
for (int r=0; r<20; r++)
{
inFile >> Ri[r];
}
}
void ResistanceSeries(int v, int I, int Ri[20])
{
float sum;
for(int j = 0; j < 20; j++)
{
sum = 0;
sum += Ri[j];
}
I = v/(float)sum;
}
void ResistanceParallel(int v, int I, int Ri[20])
{
float sum;
for(int j = 0; j < 20; j++)
{
sum = 0;
sum += 1/Ri[j];
}
I = v/(float)sum;
}
void printData(string name, string type, int n, int v, int Ri[20], float I)
{
float sum;
cout << "Circuit name: " << name << endl;
cout << "Circuit type: " << type << endl;
cout << "Circuit voltage: " << v << endl;
cout << "Total resistance R=" << sum << endl;
cout << "Total current I=" << I << endl;
}
And this is my input file (I didn't create it, it was given by instructor)