Modify the program so that it reads input temperatures from a text file (named temps.txt) instead of the keyboard. The file should allow one temperature per line. The program should end when the end of the file is reached. Modify the screen output statement so that it includes the input Celsius temperature in addition to the calculated Fahrenheit temperature. Each Celsius/Fahrenheit pair should be on its own single line of screen output. So if there are 4 temperatures in the file, there should be 4 lines of output. Make sure that you process every line in temps.txt, and when you create your own temps.txt, make sure that you press ENTER at the end of each line after typing a temperature value, just as you would for console input to a program. If your input file has 4 temperatures in it, you should create it by starting with an empty file, type a number and press ENTER, and repeat three more times. Your edit cursor should end up alone on the line after the last temperature entry. This program gets input from a named text file. Output is to the console screen, and echos the unformatted input Celsius value and prints the formatted Fahrenheit value.

Many things wrong with this program. I don't know how to get it to read 4 different lines and print them with different answers. If I have 4 lines, the answers are all the same. There is also an uninitialized local variable error for lineFromFile that I don't know how to fix. I have to resubmit this program because it was wrong. I really don't get how to fix this. I'm having a lot of trouble with loops. Please help!

#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>

using namespace std; 

#include <cmath> 

int main()
{

  double f; // degrees F
  double lineFromFile; // degrees C
  cout << fixed << setprecision(2);

  // open temps.txt for input
  ifstream fin;
  fin.open("temps.txt");
  if (!fin.good()) throw "I/O error"; 
 
      while (fin.good())
  {

    string lineFromFile;
    getline(fin, lineFromFile);
    cout << lineFromFile << " degrees Celsius is ";
    
  } // while
 
    f = 9.0 / 5 * lineFromFile + 32;
    cout << setprecision(1) << f << " degrees Fahrenheit" << endl;


    fin.close();  

  return 0;
} // main

For this assignment, I'd assume all input in the file will be valid, that is, nothing that cannot be processed as a floating point value.

That said, you could use the extraction operator ( >> ) to read from the file storing directly to a double rather than using getline( ) which reads it as a string. You would then have to convert that string to a numeric value (and there have been plenty of discussions on DaniWeb on how to do that!)

You need to put the calculation and display statements inside the loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.