C/C++从程序中向stdin添加输入?

Mil*_*lan 3 c c++ stdin input

这甚至可能吗?

让我们说代码有很多scanf行.在调试时,不是手动运行和手动添加值,而是可以用数据"输入"标准输入,这样当scanf开始读取时,它将读取输入的数据而无需与终端交互.

Ric*_*dle 13

将测试行放入文件中,然后运行如下程序:

myprogram < mytestlines.txt
Run Code Online (Sandbox Code Playgroud)

比攻击你的程序更好地以某种方式做到这一点.

在调试代码时,可以设置调试器以使用该命令行运行它.


Mar*_*off 5

为了使你的程序多一点多才多艺,你可能要考虑重写你的程序使用fscanffprintf等等。因此,它已经可以处理文件IO,而不是仅仅安慰IO; 然后,当您想从标准输入读取或写入标准输出时,您只需执行以下操作:

FILE *infile, *outfile;

if (use_console) {
    infile = stdin;
    outfile = stdout;
} else {
    infile = fopen("intest.txt", "r");
    outfile = fopen("output.txt", "w");
}
fscanf(infile, "%d", &x);
fprintf(outfile, "2*x is %d", 2*x);
Run Code Online (Sandbox Code Playgroud)

因为程序多久只处理 stdin/stdout 而不允许文件?特别是如果您最终在 shell 脚本中使用您的程序,则在命令行上指定输入和输出会更加明确。