a+b extension (C++)

OJ’s first problem is the classic a+b problem. Input two numbers and output the sum of these two numbers.
But you can't just be satisfied with this, we have to increase demand, increase demand! ! !
Not only a+b, but also continue to add or subtract other numbers, such as 1+2+3-2, and output 4.
Input
There are multiple sets of test data. Each set of test data contains a line of strings without spaces. The length of the string does not exceed 1000. The string contains only numbers, plus signs and minus signs. You can think that all numbers in the string are positive integers. , The data guarantees that the operation is legal and the intermediate result does not exceed 1000000000 during the operation.
Output
For each set of test data, output the result of a row of calculations.

#####Sample Input
1+2
1+2+3-2
3

#####Sample Output
3
4
3

The information given in the title will not result in a result that exceeds the int range during the operation, and we need to store the symbol used for the number operation when reading the string to obtain the number.
Because the title is multiple sets of input, we must initialize the character storing the arithmetic symbol with an unrelated character at the very beginning, otherwise even if you re-declare this character before each operation, the data stored in it will cause a result operation error.

code show as below:

#include<iostream>
using namespace std;
int main()
{
    
    
	string a;
	while(cin>>a)
	{
    
    
		int q=0;
		char f='.';//一定要初始化
		int sum=0;   
		int flag=0;
		for(int i=0;i<a.length();i++)
		{
    
    
			if(a[i]<='9'&&a[i]>='0')
			{
    
    
				q=q*10+a[i]-'0';
			}
			else
			{
    
    
				if(flag==0)
				{
    
    	
					sum+=q;
					flag=1;
				}
				if(f=='+')
				sum+=q;
				else if(f=='-')
				sum-=q;
				f=a[i];
				q=0;
			}
		}
		if(flag==0)
		sum+=q;
		if(f=='+')
		sum+=q;
		else if(f=='-')
		sum-=q;
		cout<<sum<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/Huo6666/article/details/108807518