Friday 6 September 2019

Chapter 10 // Exercise 2 - Principles & Practice Using C++

Chapter 10 // Exercise 2

Write a program that creates a file of data in the form of the temperature Reading type defined in section 10.5. For testing, fill the file with at least 50 "temperature readings". Call this program store_temps.cpp and the file it creates raw_temps.txt.

Main.cpp

//--------------------------------------------//
//main.cpp
//--------------------------------------------//
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <conio.h>
using namespace std;
struct Reading
{
 int hour;
 double temperature;
};
int main()
{
 vector<Reading> temps;
 int hour;
 double temperature;
 cout << "Please enter temperatures in format HOUR TEMP. Example: 1 32.65    Press Ctrl+Z to stop.\n";
 while (cin >> hour >> temperature)
 {
  if (hour < 0 || hour > 23)
   cout << "Error. Hour out of range.\n" << endl;
  temps.push_back(Reading{ hour, temperature });
 }
 ofstream readOut{ "raw_temps.txt" };
 for (uint32_t i = 0; i < temps.size(); ++i)
  readOut << temps[i].hour << " " << temps[i].temperature << "\n";
 cout << "\nPress any key..."; _getch();
 return 0;
}




EDIT: 13/01/2020
New version on GitHub. This one has more error checking and actually parses the weird format instead of changing it. https://github.com/l-paz91/principles-practice/blob/master/Chapter%2010/Exercise%202

No comments:

Post a Comment