gpt4 book ai didi

c++ - 如何读取可能以字符串或数字开头的行?

转载 作者:搜寻专家 更新时间:2023-10-31 01:01:36 25 4
gpt4 key购买 nike

我必须从这种格式的文件中读取输入:

12 + 56
9 divided by -3
45 minus 15
Min of 2 and 1
Max of 3 and 5
34 plus 33

而且我必须以这种格式输出到另一个文件:

12 + 56 is 68
9 divided by -3 is -3
45 minus 15 is 30
Min of 2 and 1 is 1
Max of 3 and 5 is 5
34 plus 33 is 67

我以这种方式接近它,但卡在了一个点上。我已将每一行读入一个字符串,但我该如何访问字符串中的操作数,因为它们位于不同字符串中的不同位置?

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int compute(string s) {
//Not sure how to do this
return 0;
}

int main() {
ifstream in;
ofstream out;
string s1 = "Input.txt";
string s2 = "CalculationResults.txt";
string s;
int operand1, operand2, result;

in.open(s1);
out.open(s2);

if (in) {
while (getline(in, s)) {
result = compute(s);
out << s << " is " << result << endl;
}
in.close();
out.close();
} else {
cout << "\nCouldn't find the input file\n\n";
}

system("pause");
return 0;
}

最佳答案

我认为最简单的做法是读取一个字符串直到第一个空格,将其与您的命令进行比较,如果不匹配,则将其转换为数字:

if (in1 >> firstthing) {
out << firstthing << " ";

if (firstthing == "Min") {
result = compute_min(in1, out); //reads in " of " and then the numbers. Also writes.

} else if (firstthing == "Max") {
result = compute_max(in1, out); //reads in " of " and then the numbers. Also writes.

} else {
int first_operand = atoi(firstthing.c_str());
//reads in an operator, then the second operand. Also writes.
result = compute_expression(in1, out, first_operand);
}
out << " is " << result << endl;
}

各种函数体比较简单:

int compute_min(std::istream& in1, std::ofstream& out) {
std::string ofstring;
int first_operand;
std::string andstring;
int second_operand;

in1 >> ofstring >> first_operand >> andstring >> second_operand;
out << ofstring << first_operand << andstring << second_operand;

return std::min(first_operand, second_operand);
}

int compute_expression(std::istream& in1, std::ofstream& out, int first_operand) {
std::string operation;
int second_operand;

in1 >> operation >> second_operand;
out << operation << second_operand;

if (operation=="+" || operation=="plus")
return first_operand + second_operand;
else if
//more

else
throw std::runtime_error("Invalid operation "+operation);
}

关于c++ - 如何读取可能以字符串或数字开头的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28865843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com