从文件读取为stdin

时间:2012-10-20 23:34:47

标签: c++ loops file-io

说我有一个main()函数,它有一些命令, 对于前

int main()
{
  ofstream myfile;
  while(!cin.eof()){
  string command; string word;
  cin >> command;
  cin >> word;

  if (command.compare("add") == 0) {
    //do Something
   }

  if (command.compare("use") == 0){
    myfile.open(word);
    myfile >> //loop back into this loop as stdin
    myfile.close();  
  }
}

myfile的内容将为文件中的每一行都有一个“command”“word”字段..我想知道是否有办法将文件作为输入读取并将其循环回main()循环?

1 个答案:

答案 0 :(得分:2)

拆分工作:

#include <string>
#include <iostream>

void process(std::istream & is)
{
    for (std::string command, word; is >> command >> word; )
    {
        if (command == "add") { /* ... */ continue; }

        if (command == "include")
        {
            std::ifstream f(word);   // or "f(word.c_str())" pre-C++11

            if (!f) { /* error opening file! */ }

            process(f);
            continue;
        }

        // ...
    }
}

int main()
{
    process(std::cin);
}