【问题标题】:Arithmetic from an input file to an output file?从输入文件到输出文件的算术?
【发布时间】:2014-03-26 20:33:04
【问题描述】:

这是一个两部分的问题,我希望我能理解。我会根据需要进行编辑!我正在尝试编写一个程序,该程序将从输入文件中连续进行计算。文本文件将如下所示:

int + 25 10
double / 5.5 8.5
...

每个实例都以 int、double、float 等类型开头,然后是计算类型(加法、减法等),然后是两个数字。我希望能够连续读取每个并将总和、乘积等输出到输出文件中。例如,如果我们使用上面的第一个示例,文件中的输出将是:

int 25 10 = 35

我有代码可以进行以下计算:

void doAddition(ifstream &inFile) {
int num1, num2;
inFile >> num1 >> num2;
cout << num1 << num2 << " = "<< (num1+num2) << '\n'; }

唯一的问题是我不知道如何添加变量的类型(我尝试过使用字符串,但它似乎不起作用),例如“int”或“double”,所以我得到:

25 10 = 35

代替:

int 25 10 = 35

您可能看到的第二个问题是,当我真的想将信息添加到输出文件时,我目前正在使用“cout”在屏幕上显示信息。以下是更多信息:

我用来移动到下一行的:

void readToNextLine(ifstream& inFile) {
string t1, t2;
inFile >> t1 >> t2; }

我的 Main 中的代码:

ifstream inFile;
//ofstream outFile;
char ch;
int num1, num2;

inFile.open("infile.txt");
//outFile.open("outfile.txt");

if (inFile.is_open()){

    inFile >> ch;
    while (!inFile.eof())
    {
        switch (ch) 
        {
            case '+':
                doAddition(inFile);
                break;
...

如您所见,我注释掉了 ofstream 部分,因为我无法让它正常工作。有什么建议么?我现在打开了大约 10 个窗口和两本 C++ 书籍,只是想把它们合乎逻辑地放在一起!

编辑:我不确定开关是否是最好的方法。我需要程序看到“int”并意识到它是一个词。如果我使用 4 种变量类型,如 int、double、float 和 long,也许我可以让它检查每个变量的第一个字母:i、d、f、l,然后一旦它知道它可以进入 +、-、等检查。感觉如果按照逻辑执行此操作,我可以使用一系列课程需要更多时间,但我只是不确定从哪里开始。

【问题讨论】:

  • 如果需要任何其他信息或者我没有说清楚,请告诉我,我会相应地编辑我的帖子!
  • 我建议将其分解为单独的简洁问题。它对 SO 用户的回答看起来更有吸引力,也会迫使你分解它。

标签: c++ visual-studio-2012


【解决方案1】:

我真的不明白从文件中读取所有这些麻烦。 Stackoverflow 和网络上有太多的例子。也许是人们没有搜索,或者他们需要一个与其确切代码匹配的示例。

试试这个:

struct Input_Record
{
    std::string data_type_as_string;
    std::string operation;
    std::string value1_as_string;
    std::string value2_as_string;

    friend std::istream& operator>>(std::istream& inp, Input_Record& r);
};

std::istream& operator>>(std::istream& inp, Input_Record& r)
{
    inp >> r.data_type_as_string;
    inp >> r.operation;
    inp >> r.value1_as_string;
    std::getline(inp, r.value2_as_string);  // Use getline to eat the line ending.
}

// ...
Input_Record r;
while (input_file >> r)
{
  // Do stuff with r
};

如果你真的想找点乐子,你可以使用父基类和工厂模式来根据输入通用地创建对象:

class Binary_Operation // Base class for factory pattern.
{
  public:
    //! Evaluate the object and return the result as a string
    //  e.g. numbers as text
    virtual std::string evaluate(void) const = 0; 
};
class Binary_Integer_Operation : public Binary_Operation
{
  public:
    std::string evaluate(void) const
    {
        // Convert values to integers than perform the operation.
        // Convert result to string using std::istringstream.
    };
};
class Binary_Double_Operation : public Binary_Operation
{
  // See Binary_Integer_Operation above.
};

这允许您执行以下操作:

Binary_Operation * factory_create(const Input_Record& r)
{
  Binary_Operation * p_obj = nullptr;
  if (r.data_type == "int")
  {
    p_obj = new Binary_Integer_Operation;
    // Initialize fields
  }
  if (r.data_type == "double")
  {
    p_obj = new Binary_Double_Operation;
    // Initialize fields;
  }
  return p_obj;
}

您的处理循环如下所示:

Input_Record r;
while (input_file >> r)
{
  Binary_Operation * p_operation = factory_create(r);
  std::string result = p_operation->evaluate();
  cout << "result = " << result << "\n";
  delete p_operation;
}

【讨论】:

  • 这是完美的,有很多不同的东西可以修补。非常感谢!
【解决方案2】:

让我们从您提供的示例开始:

int + 25 10

“类型”和算术运算符的类型很简单,分别为std::stringchar

std::ifstream in("infile.txt");
std::string type; char op;

if (in >> type >> op)
{
    // ...
}

对于其他两个值,您还必须将它们提取为字符串,因为您首先必须找出type的值,然后才能将它们转换:

if (in >> type >> op >> a >> b) // a and b are strings

现在使用函数检查type 并将ab 转换为正确的类型:

void convertTo(std::string const& typeName, std::string const& a, std::string const& b, char op)
{
    if (typeName == "int")
    {
        int a1 = std::stoi(a),
            b2 = std::stoi(b);

         doOperation(op, a1, b2)
    } else if (typeName == "double") {
        double a1 = std::stod(a),
               b2 = std::stod(b);

        doOperation(op, a1, b2);
    } else if (typeName == "float") {
        // std::stof()
    }
}

doOperation() 是模板化的,并且是这样实现的:

template<typename T>
struct F;

template<> struct F<int> { static const std::string value = "int"; };
template<> struct F<double> { static const std::string value = "double"; };
template<> struct F<float> { static const std::string value = "float"; };

template<typename U, std::string name = F<U>::value>
void doOperation(char op, U a, U b)
{
    std::ofstream out("outfile.txt");
    switch (op)
    {
        case '+':
            out << name << " " << op << " " << (a + b);
        case '-':
            out << name << " " << op << " " << (a - b);
        case '/':
           // ...
        // ...
    }
}

【讨论】:

  • 非常感谢,这些都是很好的例子,会很有帮助!
猜你喜欢
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 2015-08-02
  • 2019-02-27
相关资源
最近更新 更多