DEV Community

Simone Aronica
Simone Aronica

Posted on • Updated on


C++ read file from stdin

I've started to learn c++ and I need a way to read a file line by line directly from stdin. Now what I've tried is this:

freopen("input.txt", "r", stdin);
string buffer;
vector<int> temp = {};
getline(cin, buffer);
for(int elem : buffer) 
  if(elem != ' ')
    temp.push_back(elem - '0');
*dest = temp;

but when I run this code, the console waits for me to insert data via cli instead of reading it from stdin.
What can I do?

Oldest comments (2)

sfiquet profile image
Sylvie Fiquet

I'm not super familiar with modern C++ but I believe stdin's purpose is for getting input from the console/terminal. So I don't understand why you would read a file from stdin and in any case why you would redefine stdin. Maybe you're supposed to type something like this on the CLI:

myprogram < input.txt

so that file input.txt ends up in the stdin for the program? That's all I can think of.

gugglegum profile image
Paul Melekhov

When you didn't define any file as input or pipe from another app, keyboard input is your stdin.

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git