Total C++ beginner and as the title says, i'm trying to read a .txt file looping through line by line whilst performing a calculation on the data of the line before moving to the next line.
int main() {
ifstream in_file;
string name;
int kiloWatt{};
int amperage{};
int cores{3};
int voltage{480};
double powerFactor{0.8};
double efficiency{0.93};
double root{};
in_file.open("../test.txt");
if(!in_file){
cerr <<"Problem opening file" << endl;
return 1;
}
while (in_file >> name >> kiloWatt){
root = sqrt(cores);
amperage = (kiloWatt*1000)/(root*voltage*powerFactor*efficiency);
cout << setw(10) << name
<< setw(10) << kiloWatt
<< setw(10) << amperage
<< setw(10) << root
<< endl;
}
in_file.close();
return 0;
}
this works however it closes the loop after the first line and so displays only one line.... anyone point me in the direction of why? Many thanks.
The txt file its referencing would look something like:
name1 23.5
name2 45.6
name3 234.8
kiloWatt
is an int, so on the first line, it'll read 23
, see a non-integer character and stop. The next name
will be ".5"
, and you'll try to read "name2"
into kiloWatt
, which will fail, since it's not a number--breaking your loop.
Change kiloWatt
to be a double to fix this.