c++ - 作为标准输入从文件中读取

标签 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 的内容将为文件中的每一行都有一个“命令”“单词”字段。我想知道是否有一种方法可以将文件作为输入读取并将其循环回 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);
}

关于c++ - 作为标准输入从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993621/

相关文章:

C++ 11 随机数生成不起作用

c++ - 程序旨在计算数组中有多少重复项。但是,它返回错误的频率值

c++ - 从文件读取 C++ 程序停止工作

java - 转换具有文本初始化的文件后,我的字节数组充满零的原因是什么?

c++ - 如何初始化一个静态成员

c++ - 如何对C++中一个函数的所有重载进行 "export"?

java - 使用 for 循环返回串联字符串

javascript - 如何搜索 JSON 并查找特定名称的每次出现(带增量)

php - 如何自动化数据收集而不卡住 10%

java - 在多行文本文件上使用 StringTokenizer 时出错