[英]How to read lines from a file as well as from std::cin?
我正在编写一个程序,它从文件中获取要处理的文本行,用户将其名称作为参数传递,例如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:我希望有可能在程序的主循环中更新输入源(见下文)。
第一个示例中的段错误是由于悬空指针引起的; 在您调用std::cin.rdbuf(ifs.rdbuf())
, ifs
被销毁。 您应该按照@NathanOliver 的建议进行操作并编写一个采用istream&
的函数:
#include <iostream>
#include <fstream>
#include <string>
void foo(std::istream& stream) {
std::string line;
while (std::getline(stream, line)) {
// do work
}
}
int main(int argc, char* argv[]) {
if (argc == 2) {
std::ifstream file(argv[1]);
foo(file);
} else {
foo(std::cin);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.