从文本文件或标准输入读取

8
我有一个程序,基本上是读取文本文件并计算每行中每个单词出现的次数。使用 ifstream 从文本文件读取时一切正常,但是如果没有在命令行输入文件名,则需要从 stdin 中读取。
我目前使用以下代码打开和读取文件:
map<string, map<int,int>,compare> tokens;
ifstream text;
string line;
int count = 1;

if (argc > 1){
    try{
        text.open(argv[1]);
    }
    catch (runtime_error& x){
        cerr << x.what() << '\n';
    }

    // Read file one line at a time, replacing non-desired char's with spaces
    while (getline(text, line)){
        replace_if(line.begin(), line.end(), my_predicate, ' ');

        istringstream iss(line);    
        // Parse line on white space, storing values into tokens map
        while (iss >> line){                
            ++tokens[line][count];
        }
        ++count;
    }
}

else{
while (cin) {
    getline(cin, line);
    replace_if(line.begin(), line.end(), my_predicate, ' ');

    istringstream iss(line);
    // Parse line on white space, storing values into tokens map
    while (iss >> line){
        ++tokens[line][count];
    }
    ++count;
}

有没有一种方法可以将cin分配给ifstream,并在argc > 1失败时简单地添加else语句,而不是像这样重复代码?我还没有找到一种方法来做到这一点。

我建议您获取C++11标准加上一些小的编辑更改。 - Deduplicator
3个回答

13

将读取部分作为其自己的函数。将ifstreamcin传递给它。

void readData(std::istream& in)
{
   // Do the necessary work to read the data.
}

int main(int argc, char** argv)
{
   if ( argc > 1 )
   {
      // The input file has been passed in the command line.
      // Read the data from it.
      std::ifstream ifile(argv[1]);
      if ( ifile )
      {
         readData(ifile);
      }
      else
      {
         // Deal with error condition
      }
   }
   else
   {
      // No input file has been passed in the command line.
      // Read the data from stdin (std::cin).
      readData(std::cin);
   }

   // Do the needful to process the data.
}

1
你不能将cin赋值给ifstream。
但是你可以重新打开cin来读取某个文件。
无论如何,更好的方法是模块化你的代码,并只使用std::istream&

1
我刚刚提供了一种简便的方法,使程序在给定文件的情况下可以读取文件,否则使用标准输入,并正确关闭文件。
#include <fstream>
#include <iostream>
#include <memory>
#include <string>

int main(int argc, char* argv[]) {
    auto fp_deletor = [](std::istream* is_ptr) {
        if (is_ptr && is_ptr != &std::cin) {
            static_cast<std::ifstream*>(is_ptr)->close();
            delete is_ptr;
            std::cerr << "destroy fp.\n"; 
        }
    };

    std::unique_ptr<std::istream, decltype(fp_deletor)> is_ptr{nullptr, fp_deletor};
    if (argc > 2) {
        std::cerr << "usage: " << argv[0] << "[input-file]";
        return -1;
    } else if (argc == 1) {
        std::cerr << "using stdin as input.\n";
        is_ptr.reset(&std::cin); 
    } else {
        is_ptr.reset(new std::ifstream(argv[1]));
    }

    std::string line;
    while (std::getline(*is_ptr, line)) {
        // your logic....
    }

    // just return, unique_ptr manage the istream
    return 0;
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接