【发布时间】:2021-10-21 00:37:03
【问题描述】:
我正在编写一个程序,它从文件中获取要使用的文本行,用户将其名称作为参数传递,例如program <name of the file>。但如果未提供名称,则从std::cin 动态获取输入。我试过的:
- 重定向缓冲区(为什么会导致段错误)
if (argc == 2) {
std::ifstream ifs(argv[1]);
if (!ifs)
std::cerr << "couldn't open " << argv[1] << " for reading" << '\n';
std::cin.rdbuf(ifs.rdbuf());
}
for (;;) {
std::string line;
if (!std::getline(std::cin, line)) // Here the segfault happens
break;
- 创建一个变量,其中存储了输入源
std::ifstream ifs;
if (argc == 2) {
ifs.open(argv[1]);
if (!ifs)
std::cerr << "couldn't open " << argv[1] << " for reading" << '\n';
} else
ifs = std::cin; // Doesn't work because of the different types
for (;;) {
std::string line;
if (!std::getline(ifs, line))
break;
现在我正在考虑对文件结构/描述符做一些事情。怎么办?
UPD:我希望能够在程序的主循环中更新输入源(见下文)。
【问题讨论】:
-
将您的代码写入一个接受
ostream&并输出到该函数的函数中。然后,您可以将您希望使用的流传递给该函数。 -
编写一个接受
std::istream &并从该流中读取的函数。如果您的程序需要从std::cin读取,则将std::cin传递给该函数。如果您的程序需要从文件中读取,则将该文件作为std::ifstream打开并将该流传递给您的函数。
标签: c++