题解 | #实现简单计算器功能#
实现简单计算器功能
https://www.nowcoder.com/practice/e7c08272a4b7497fb990ce7abb1ee952
#include <cstdlib>
#include <iostream>
using namespace std;
#include <cstring>
#include <sstream>
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
// write your code here......
string oper;
string sr1, sr2;
int s = 0;
for (int i = 0; i < strlen(str); i++)
{
if (!isspace(str[i]))
{
if (s == 0)
{
oper += str[i];
}
else if (s == 1)
{
sr1 += str[i];
}
else
{
sr2 += str[i];
}
}
else
{
s += 1;
}
}
stringstream ss;
int r1 = stoi(sr1);
int r2 = stoi(sr2);
if (-100 <= r1 && r1 <= 100 && -100 <= r2 && r2 <= 100)
{
if (!strcasecmp(oper.c_str(), "add"))
{
cout << r1 + r2 << endl;
}
else if (!strcasecmp(oper.c_str(), "sub"))
{
cout << r1 - r2 << endl;
}
else if (!strcasecmp(oper.c_str(), "mul"))
{
cout << r1 * r2 << endl;
}
else if (!strcasecmp(oper.c_str(), "div"))
{
if (r2 == 0)
{
cout << "Error" << endl;
}
else
{
cout << r1 / r2 << endl;
}
}
}
return 0;
}
