1059. 表达式求值
题目描述
计算仅含有加法计算的表达式的值。该表达式长度不超过250,中间没有空格与括号,并且计算结果在整数范围内。
输入
输入表达式。
输出
输出表达式的值。
样例输入
12+23+21
样例输出
56
数据范围限制
C++代码
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int GetInt(string strText)
{
int n = 0;
stringstream os;
os << strText;
os >> n;
return n;
}
int main()
{
const int max_len = 250;
char szBuf[max_len+1];
cin.getline(szBuf, max_len);
string strText = szBuf;
string strResult;
istringstream istr(strText);
int sum = 0;
while(!istr.eof())
{
getline(istr, strResult, '+');
sum += GetInt(strResult);
}
cout << sum << endl;
return 0;
}
还有另一种求解方法,没有把表达式当作字符串来处理,简单粗暴,直接有效。
#include <iostream>
using namespace std;
int main()
{
int addend, sum = 0;
char ch;
while (1)
{
cin >> addend;
sum += addend;
cin.get(ch);
if (ch != '+')
{
break;
}
}
cout << sum << endl;
return 0;
}