如何在 c++ 中使用输入重定向添加整数

How to add integers using input redirection in c++

本文关键字:输入 重定向 添加 整数 c++      更新时间:2023-10-16

我正在做一个作业,在其中我创建了一个名为formula的文件.txt其中包含以下内容:

100 + 50 - 25 + 0 + 123 - 1

现在我必须使用输入重定向,以便文件读取整数并给我上述整数的总和。

我尝试包含字符串以及将整数的类型更改为 char 以处理 + 和 - 符号。我知道 cin 接受输入并跳过空格,但我的总和不是所需的总和。

#include <iostream>
#include <string>
using namespace std;
int main()
{
  int sum = 0; //sets sum to 0
  char input=0;// sets input to 0
  while(cin>>input) // reads inputs
  {
      sum+=input; // adds inputs 
  }
  cout << sum << endl; // adds input
}

我应该得到答案 247相反,我得到了 835

首先,你对 char s 使用 >>,这会丢弃空格。

字符100+50-25+0+123-1的 ascii 值为:

49, 48, 48, 43, 53, 48, 45, 50, 53, 43, 48, 43, 49, 50, 51, 45, 49

他们的总和是815.这解释了您的输出。您应该阅读数字和运算符,而不是单个字符。

要读取文件,可以使用如下std::ifstream

#include <fstream>
#include <string>
int main()
{
    std::ifstream ifs{"file name here"}; // NOTE: put your own file name here!!
    int sum;
    ifs >> sum;
    for (char c; ifs >> c;)
    {
        int num;
        ifs >> num;
        if (c == '+')
            sum += num;
        if (c == '-')
            sum -= num;
    }
    std::cout << sum << "n";
}

或者,您也可以使用系统提供的管道语法,这可能是您所说的"重定向"。

虽然另一个回答了你的问题, 这是使用 getline 的方法之一。假定文件只有一行。

#include <fstream>
#include <sstream>
#include <string>
enum class Operation {
    ADD,
    SUBTRACT
};
int main() {
    std::ifstream fin {"<file to be opened>"};
    std::string str;
    std::getline(fin, str);
    std::istringstream sstr(str);
    std::string op;
    int ans = 0;
    Operation lastOperation = Operation::ADD;
    while (sstr >> op) {
        if (op == "+") {
            lastOperation = Operation::ADD;
        } else if (op == "-") {
            lastOperation = Operation::SUBTRACT;
        } else {
            int num = std::stoi(op);
            if (lastOperation == Operation::ADD) {
                ans += num;
            } else if (lastOperation == Operation::SUBTRACT) {
                ans -= num;
            }
        }
    }
    cout << ans << "n";
}