如何在 c++ 中使用输入重定向添加整数
How to add integers using input redirection in c++
我正在做一个作业,在其中我创建了一个名为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";
}
相关文章:
- 编写时C++中的输入重定向问题
- 获取通过重定向传入的输入文件的名称?
- 使用 dup2() 进行输入重定向
- 重定向输入和输出时如何处理主文件I/O?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 当使用带有stdin和stdout重定向的双进程管道时,如何避免stdin上的重复输入
- 如何将输入重定向与特殊整数作为分隔线和直至EOF
- 输入重定向读取整数和char C
- C++输入重定向导致文件参数工作时出错
- 如何在 c++ 中使用输入重定向添加整数
- 在while循环中使用输入重定向
- 如何在c++中从shell中获取作为输入重定向的文件名
- 使用输入重定向,如何在 C 中读取文件和获取字符串
- 带有 execv 和输入重定向的 C++ 流水线命令
- 如何处理输入重定向
- Python将输入重定向到子进程
- 检查CPP程序中的输入重定向
- C shell输入重定向保持打开状态
- C++检测输入重定向
- 通过输入重定向读取二进制文件c++的最佳方式