DEV Community

Simone Aronica
Simone Aronica

Posted on • Edited on

2 1

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?

Top comments (2)

Collapse
 
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.

Collapse
 
gugglegum profile image
Paul Melekhov

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →