#include <iostream>
#include <string>
#include <sstream>
using namespace std;
double performOperation(const string &opt, int num1, int num2) {
if (opt == "add") return num1 + num2;
else if (opt == "sub") return num1 - num2;
else if (opt == "mul") return num1 * num2;
else if (opt == "div") {
if (num2 == 0) {
cout << "Error" << endl;
exit(EXIT_FAILURE);
}
return num1 / num2;
} else {
cout << "Error: Invalid operation.\n";
exit(EXIT_FAILURE);
}
}
int main() {
char str[100] = {0};
cin.getline(str, sizeof(str));
// write your code here......
string input = str;
string opt;
int num1, num2;
istringstream iss(input);
iss >> opt >> num1 >> num2;
for (char &c: opt) {
c = tolower(c);
}
double res = performOperation(opt, num1, num2);
cout << res << endl;
return 0;
}
虽然题目未说明是否允许使用字符串分割的类,但为了后续的学习和规范地编码,了解一下也未尝不可



京公网安备 11010502036488号