I have written a program that accepts input from a .txt
file and outputs the sum. I have correctly gotten the sum of the numbers in one line. I need outputs for all the lines in the file.
The requirements for this are to include a semicolon to indicate end of line in the .txt
file.
#include <iostream>
#include <string>
#include<fstream>
using namespace std;
int main()
{
std::ifstream ifs{"formula.txt"};
int sum = 0;
ifs >> sum;
//int input = 0;
{
for (char a; ifs >> a;)
{
int num;
ifs >> num;
if(a == '+')
{
sum += num;
}
if(a == '-')
{
sum -= num;
}
if( a== ';')
{
sum += num;
sum -= num;
}
}
cout << sum << endl;
}
}
the line cout << sum << endl;
is put after the for, so you write only one value at the end rather than the value each time ';' is reach
In
if( a== ';')
{
sum+= num;
sum-= num;
}
sum in unchanged except in case of an overflow
must be something like
if( a== ';')
{
cout << sum << endl;
sum = 0;
}
because the ';' marks the end of a formula.
Your loop cannot manage a form like 10 + 3 + 0 + 25
, because each turn of for you always manage an operator then a number
The input is 15;10 ...
and than cannot be managed, you read 15 and save it in sum, then you read ';' and assign a with, then you read 10 and assign num with so 10 is lost etc
A proposal :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs("formula.txt");
if (!ifs.is_open()) {
cout << "cannot open formula.txt" << endl;
return -1;
}
int val;
while (ifs >> val)
{
char op;
while (ifs >> op)
{
if (op == ';')
{
cout << val << endl;
break;
}
int num;
if (! (ifs >> num)) {
cout << "unexpected EOF" << endl;
return -1;
}
if (op == '+')
{
val += num;
}
else if (op == '-')
{
val -= num;
}
else {
cout <<"invalid operator '" << op << '\'' << endl;
return -1;
}
}
}
return 0;
}
Compilation and execution
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra s.cc
pi@raspberrypi:/tmp $ cat formula.txt
15;10+3+0+25;5+6-7-8+9+10-11;
pi@raspberrypi:/tmp $ ./a.out
15
38
4
pi@raspberrypi:/tmp $