C++使用文件重定向

使用IDE工具: visual studio 2017 

使用的Sales_item.h 文件:https://github.com/Mooophy/Cpp-Primer/blob/master/include/Sales_item.h

《Primer c++》 19页中,避免重复无聊的数据输入,使用文件的重定向,大体意思就是从文本中读取需要的数据,而不是窗口中一行一行的输入

内容样例给出: $addItem  <infile> outfile        

其中 addItem 是程序编译后的可执行文件,尖括号中是数据的源文件,outfile是要输出的文件,需要注意的是这里的输入和输出文件需要和exe文件在同一目录下

1、在window命令行窗口中使用指令完成

在开始菜单->安装路径下启动 [ x64 Native Tools Command Prompt for VS 2017] 

 

切换到 可执行程序的路径下,执行【 vshello  <input.txt> output.txt 】

其中vshello  是项目debug 文件夹中的 可执行文件,input.txt 和 output.txt 也一同放在该文件夹下。

input.txt 中放有两行记录:

x-78 3 20.00
x-78 2 21

当命令执行完成后,可在output.txt 中看到输出结果。

但是这种方式完全是在命令行中,我们想断点调试完全不行,所以想着可以试着从代码中读取文件,然后进行计算

2、在代码中读取数据文件

所使用的涉及到第八章中的IO库 fstream 的使用,

#include <iostream>
using std::cin; using std::cout; using std::endl;
#include <string>
using std::string;
#include "Sales_item.h"
#include <fstream>

int main()
{
	std::ifstream in("input.txt");
	std::streambuf *cinbackup;
	cinbackup = cin.rdbuf(in.rdbuf());

	Sales_item item1, item2;
	cin >> item1 >> item2;
	cout << item1 + item2 << endl;

	return 0;
}

  

需要注意的是文件input.txt 放在的位置是项目下,而非前面debug文件夹中。

原文地址:https://www.cnblogs.com/hcklqy/p/14303026.html