#include <iostream>
#include <fstream>
#include <string>
int main()
{
constchar* const file_name = "information.txt" ;
{
// create the test file
std::ofstream out_file(file_name) ;
out_file << " Height Radius Calculation-Type \n"
<< " 1.0 1.0 C \n 1.0 1.0 V \n 1.0 1.0 S \n 1.0 1.0 D \n 1010.0 250.0 C \n "
<< "12.3 3.25 V \n 123.0 43.0 S \n 12.3 3.25 K \n 1.12 2.13 C \n"
<< " -999\n" ; // The last entry in the file is a sentinel to indicate the end of data
// (something like -999)
}
{
// sanity check: verify that the file was created correctly
std::ifstream in_file(file_name) ;
std::cout << "contents of test file\n-------------------\n" << in_file.rdbuf() ;
}
{
std::ifstream file(file_name) ; // open the file for input
// read the first line and print it
std::string first_line ;
std::getline( file, first_line ) ;
std::cout << first_line << '\n' ;
double height ; // The first number in each line is the height
double radius ; // the second number is the radius
char calculation_type ; // and the last number is the calculation type (C/V/S)
// for each height read in, till the sentinel (-999) to indicate the end of data
while( file >> height && height != -999 )
{
file >> radius // read in the radius
>> calculation_type ; // and the calculation type
switch(calculation_type) // switch on the calculation type
{
case'C' : // circumference
// ...
break ;
case'V' : // volume
// ...
break ;
case'S' : // surface area
// ...
break ;
default : // invalid
std::cout << "invalid calculation type\n" ;
// ...
}
}
}
}
The program to create the output file will work, but from line 23 to 31 you have used to many '\t's and have extra spaces between the pieces of information. Just one space is needed between each piece of information.
The code for reading the file will work to make sure you can read the file.
After case for each one do I just start putting in the equations and then a cout statement to display the solutions? Thank you guys for the help! Also, the notes from both of you are helping me understand this a lot better.
Alright guys! It works :D YAY!! Thank you for all your help! I only have one last question! It is displaying all the data and I only need it to display one line. Just the first line that says Height Radius and Calculation Type. Do you know what I have to change to do this? I tried a lot of things yesterday and couldn't figure it out. Here is the final copy of the code.
What you need to change is on line 19. Remove or comment out the part of the line << in_file.rdbuf(). Not quite sure how it is working, but it does print out the entire file.