In: Computer Science
In Programming Challenge 12 of Chapter 3, you were asked to write a program that converts a Celsius temperature to Fahrenheit. Modify that program so it uses a loop to display a table of the Celsius temperatures 0–20, and their Fahrenheit equivalents. Display table on screen and it a .txt file.
c++
Code:
#include <iostream>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
int Celsius=0;
fstream file;
// creating and opening a text file
file.open("a.txt",ios::out);
// if file is not created then show error
if(!file){
cout<<"Error"<<endl;
exit(1);
}
cout<<"Celsius"<<setw(15)<<"fahrenheit"<<endl;
// Writing to the file
file<<"Celsius"<<setw(15)<<"fahrenheit"<<endl;
for(Celsius=0;Celsius<=20;Celsius++){
// Converting Celsius to fahrenheit
float fahrenheit=(Celsius*9.0)/5.0+32;
std::cout << Celsius<<setw(15)<<fahrenheit << std::endl;
// Writing to text file
file<<Celsius<<setw(15)<<fahrenheit<<endl;
}
// Closing the file
file.close();
return 0;
}
Screenshot of the code:
Screenshot of the output:
a.txt file :