.txt calculation

Aug 25, 2013 at 3:19am
I put all the data into a .txt file.
How do I use the information from the .txt file and make some calculation?

inside the .txt file

SQUARE 10.2 12.3
RECTANGLE 5.6 6.7

I have to calculate the area of both shapes.
Last edited on Aug 25, 2013 at 3:51am
Aug 25, 2013 at 6:58am
1) what are the two numbers in front of square?
2) do you want to take two lines of input only or more?

Please explain more
Aug 25, 2013 at 7:14am
If the format is always the same:
1) Read in the name of the shape
2) You could store the name for like when you print: "SQUARE has an area of: "
3) Read in the next two numbers and store them in their own variables
4) Now multiply those two variables to get the area.
5) Repeat steps 1-4 (you can use the same variables, because they will be overwritten with/reassigned the new values).

Simple?
Aug 26, 2013 at 12:18am
how do I read the numbers from the .txt file? can you be more specific and ? give me some examples? Thanks.
Aug 26, 2013 at 1:20am
The standard's file input class is std::ifstream, which is under the <fstream> header. One of the best parts about fstream objects is that you can treat them like cout/cin.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream>

int main(){
   std::string filepath("data.txt");//File Name or File Path
   std::ifstream data(filepath); //Opens the file

   if( !data.is_open()) return 2; //Make sure the file was opened successfully

   while(data.good()){//Will stop the loop if there is any problem or if we reach the end of the file
      std::string shape("");
      double side1(0), side2(0);

      data >> shape >> side1 >> side2; //Just like using cin
//...Do stuff with new data...
   }
   data.close(); //Close the file. Not actually necessary, but it is good practice

   return 0;
}


How you read in the data, though, depends on the format the data is written in.
Topic archived. No new replies allowed.