How to make the file operational

As you can see im trying to make the example.txt file mathematical operational. Cause for example in the text file it says there "2+3" then i use getline to get "2+3" in the program and the program screen should display "5". but all i get for print is still "2+3" how will i make 2+3 operational and not just printing itself?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<fstream>
#include<iostream>
#include<string>
using namespace std;

int main()
{
string c;    
string line;    
ifstream a_file ( "example.txt" );

if ( !a_file.is_open() ) {
  // The file could not be opened
}
else {
     getline (a_file,line);
     c = line;
     cout<<c<<endl;
     }
     a_file.close();
     
     
     return 0;
     }
you will have to parse the string and do the operations yourself.


if its always operand operator operand you can use operator >> instead of getline

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int operand1 , operand2;
char operation;
int result;
while(a_file >> operand1 >> operation >> operand2)
{
    switch(operation)
    {
        case '+':
           result = operand1 + operand2;
            break;
        case '-':
         //ect...
         //be sure to check for division by 0 though in the division
    }
    std::cout << operand1 << operation << operand2 << " = " << result << std::endl;
}
Topic archived. No new replies allowed.