用c++
时间: 2023-07-01 09:22:15 浏览: 54
好的,以下是使用 C++ 实现的代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 读取题目文件
ifstream fin("question.txt");
string line;
int a, b;
char op;
while (getline(fin, line)) {
// 对题目进行求解
sscanf(line.c_str(), "%d%c%d=", &a, &op, &b);
int answer;
switch (op) {
case '+':
answer = a + b;
break;
case '-':
answer = a - b;
break;
case '*':
answer = a * b;
break;
case '/':
answer = a / b;
break;
default:
continue;
}
// 将答案写入文件
ofstream fout("answer.txt", ios::app);
fout << a << op << b << "=" << answer << endl;
fout.close();
}
fin.close();
return 0;
}
```
以上代码与之前的 Python 代码基本相同,只是使用了 C++ 的文件读写函数和字符串处理函数。`getline()` 函数逐行读取题目文件中的题目,然后使用 `sscanf()` 函数对每行题目进行解析,得到题目中的数字和运算符。计算完答案后,使用 `ofstream` 类型的文件流写入答案文件中。为了避免覆盖已有的答案,我们同样使用了 `ios::app` 模式打开答案文件。
希望这个代码能够帮助到您!