用c++写
时间: 2023-07-01 15:22:15 浏览: 41
好的,以下是 C++ 代码实现:
```cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
// 读取题目文件
vector<string> questions;
ifstream infile("question.txt");
string line;
while (getline(infile, line)) {
questions.push_back(line);
}
// 计算答案
vector<string> answers;
for (string q : questions) {
stringstream ss(q); // 将字符串转为流
int left, right;
char op, equal;
ss >> left >> op >> right >> equal;
int ans;
switch (op) {
case '+':
ans = left + right;
break;
case '-':
ans = left - right;
break;
case '*':
ans = left * right;
break;
case '/':
ans = left / right; // 整除
break;
default:
cout << "Invalid operator: " << op << endl;
return 1;
}
answers.push_back(q + to_string(ans) + "\n");
}
// 将答案写入文件
ofstream outfile("answer.txt");
for (string ans : answers) {
outfile << ans;
}
return 0;
}
```
代码中使用了 STL 中的容器 vector 和文件流 ifstream, ofstream。其中,`getline()` 方法用于逐行读取文件内容,`stringstream` 类可以将字符串转为流,`to_string()` 方法用于将整数转为字符串。另外,`switch` 语句用于判断运算符,当运算符不是加减乘除中的任意一个时,输出错误信息并退出程序。
需要注意的是,在 C++ 中整数相除默认会进行截断,即保留整除部分。因此,不需要使用 `//` 运算符。