[英]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.