从文件中读取为stdin

Reading from file as stdin

本文关键字:stdin 读取 文件      更新时间:2023-10-16

说我有一个具有某些命令的main()函数,对于ex

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的内容将为文件中的每一行带有一个"命令"字段。

拆分工作:

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