簡體   English   中英

從文件讀取為stdin

[英]Reading from file as stdin

說我有一個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()循環?

拆分工作:

#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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM