In: Computer Science
9. #include
<fstream>
#include <iostream>
using namespace std;
int main()
{
float bmi;
ifstream inFile;
inFile.open("bmi.txt");
while (!inFile.eof())
{
inFile >>
bmi;
if( bmi <
18.5)
{
cout << bmi << " is underweight " ;
}
else if( bmi >= 18.5
&& bmi <= 24.9)
{
cout << bmi << " is in normal range " ;
}
else if( bmi >= 25.0
&& bmi <= 29.9)
{
cout << bmi << " is overweight " ;
}
else if( bmi >=
30)
{
cout << bmi << " is obese " ;
}
cout <<
endl;
}
return 0;
}
bmi.txt looks like below:
25.0
17.3
23.1
37.0
What will be the output when the above code runs with the above bmi.txt file.
Here is the solution to above problem in C++. Please read the code comments for more information
Please give a thumbs up!!!
Explanation
1) inFile.open will open the file bmi.txt
2) while(!inFile.eof()) will execute the code till the end of of bmi.txt is reached and inFile>>bmi will read a float value from bmi.txt one at a time
3) after that if condition is executed based on the value in the file
4) the first value in bmi.txt is 25 hence overweight is printed , second value is 17.3 hence underweight is printed
5) For 23.1 normal weight is printed , last value is 37.0 hence obese is printed
6) Note that the last value in bmi.txt is printed twice
C++ Code
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
float bmi;
ifstream inFile;
inFile.open("bmi.txt");
while (!inFile.eof())
{
inFile >> bmi;
if( bmi < 18.5)
{
cout << bmi << " is underweight " ;
}
else if( bmi >= 18.5 && bmi <= 24.9)
{
cout << bmi << " is in normal range " ;
}
else if( bmi >= 25.0 && bmi <= 29.9)
{
cout << bmi << " is overweight " ;
}
else if( bmi >= 30)
{
cout << bmi << " is obese " ;
}
cout << endl;
}
return 0;
}
Screenshot of output