.txt calculation

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
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
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?
how do I read the numbers from the .txt file? can you be more specific and ? give me some examples? Thanks.
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.