0

Currently I have code that uses cin to get the name of the file to be used as input when the program is executed. I would like to have it so that when i run the program i can add the file redirection and the filename and run it as such: ./a.out < file.txt. How can i feed my file into my code using redirection.

this is an example of how i am currently taking input:

int main(){
  
    std::string filename;
 std::cin >> filename;
 std::ifstream f(filename.c_str());
  
 }
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Ryan
  • 21
  • 1
  • 3

1 Answers1

0

Do it like this

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string line;

    std::cout << "received " << std::endl;

    while(std::getline(std::cin, line))
    {
        std::cout << line  << std::endl;
    }

    std::cout << "on stdin" << std::endl;
}

You do not need to open the file yourself as the file content is passed to you on stdin as a result of using < on the command line.

This code has a drawback that if you do not input anything on stdin it freezes. Detecting that stdin is empty can only be achieved in a non portable manner (see here).

It would be better to accept your filename as a normal command line argument and open it inside your program.

Community
  • 1
  • 1
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61