knlao
knlao

Reputation: 3

C++ string calculator

I have been doing exercises on some online judges, and I encounter this question with this default answer.

Question description:
Finally, Hansbug has finally reached the moment to do the last math problem, and there are a bunch of messy addition and subtraction equations in front of him. Obviously success is at hand. But his brain cells have been exhausted, so this important task is left to you.

Input format:
One line, containing a string of addition and subtraction polynomials (the range of each item is 0-32767).

Output format:
An integer, which is the result of the calculation (guarantee that the result of the calculation will not exceed the range of the long integer).

Input and output sample:

Enter #1: 
1+2-3
Output #1: 
0

And the default answer is :

#include<bits/stdc++.h>

using namespace std;
int ans;
int c;

int main() {
    while (cin >> c)
        ans += c;
    cout << ans;
    return 0;
}

How is this even possible!?

Upvotes: 0

Views: 715

Answers (1)

Roman Pavelka
Roman Pavelka

Reputation: 4171

All right, let's try it, let's put there some expression with addition and subtraction of ints only, after that press Return, then ctrl+D (end of input):

$ ./a.out 
111-222+1
-110$

The loop while (cin >> c) will parse integers including the sign one by one using iostream capabilities until an end of input (you also have to terminate the last number by pressing Return, effectively putting the newline there and triggering the last cin >> c).

Upvotes: 1

Related Questions