当您调用程序时a.out < file.txt,您要求shell将file.txt内容作为标准输入来管道,a.out 而不是让键盘提供标准输入.如果不适合你,然后添加一个命令行参数来指定文件名,使用的ifstream将其打开,从而不是阅读cin,使用cin的键盘输入.
例如:
int main(int argc, const char* argv[])
{
if (argc != 2)
{
std::cerr << "usage: " << argv[0] << " <filename>\n";
exit(1);
}
const char* filename = argv[1];
if (std::ifstream in(filename))
{
// process the file content, e.g.
std::string line;
while (getline(in, line))
std::cout << "read '" << line << "'\n";
}
else
{
std::cerr << "unable to open \"" << filename << "\"\n";
exit(1);
}
// can still read from std::cin down here...
}
Run Code Online (Sandbox Code Playgroud)