文件重定向
当你测试程序时,反复从键盘敲入,是非常乏味和低效的,这个时候就可以使用文件重定向机制,这种机制允许我们将标准输入和标准输出与命名文件关联起来。
一个简单的C++程序
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word;
while (cin >> word)
{
cout << "word read is: " << word << endl;
}
cout << "no more words to read!" << endl;
return 0;
}
使用文件重定向
当程序运行时,每次输入一个字符串,然后输出,如果改用文件重定向,进入到cmd环境下,找到hello.exe(假如是hello.exe)文件的所在的目录,新建一个input.txt,(由文件输入,而不是在屏幕上输入——输入重定向)。在命令提示符下输入hello.exe < input.txt
回车,会将input.txt中的文件内容读出,显示在屏幕上。如果不想显示在屏幕上,在命令提示符下输入 hello.exe < input.txt > output.txt
,结果将存入output.txt中,如果想把每次结果追加到output.txt中,而不是覆盖,在命令提示符下输入 hello.exe < input.txt >> output.txt
。
使用脚本
如果每次都需要在命令行输入,这就太麻烦了,所以想到了bat,新建一个bat文件例如start.bat,在里面写入
@echo off
@REM 这是注释,cd 后面是 *.exe的目录
cd "/Debug"
cmd /c "Hello.exe < input.txt > output.txt"
echo end.
pause
每次直接运行bat就ok了,根据需要改动即可。