John Smith
John Smith

Reputation: 27

Reading from file as stdin

say i have a main() function that has some commands, for 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();  
  }
}

the contents of myfile will have a "command" "word" field for each line in the file.. I was wondering if there was a way to read the file as input and loop it back into the main() loop?

Upvotes: 0

Views: 1587

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477512

Split the work:

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

Upvotes: 2

Related Questions