-1

My main.cpp

#include <iostream>
#include <fstream>

int main(int argc, char* argv[]) {
   std::string filename;
   std::cin >> filename;
   std::ifstream inf(filename);
   std::string line;
   while(std::getline(inf, line)) {
         std::cout << line << std::endl;
   }

   return 0;
}

Trying to read:

main < somefile.txt

I was old that when you write, < or > it's a directive for stdout/stdin (cin/cout). I want to read line by line, and check for EOF, in C++.

EDIT: Nothing really happens. Are there any C++ 20 recommendations for faster C++, I know C is normally faster.

file.txt:

300 55 12
56 99 -21
John Smith
  • 725
  • 3
  • 10
  • 31

1 Answers1

3

File redirection with < sends it directly to stdin, so you don't need to create a std::ifstream.

#include <iostream>

int main(int argc, char* argv[]) {
   std::string line;
   while(std::getline(std::cin, line)) {
         std::cout << line << std::endl;
   }

   return 0;
}
SuperStormer
  • 3,554
  • 4
  • 16
  • 29
  • I wrote code like this, the writing of code isn't a big issue mate. But, I am trying to figure out how I can check EOF and break. – John Smith Aug 29 '20 at 19:22
  • 2
    Your code already does that right here: `while(std::getline(std::cin, line)) {` std::getline returns false when you hit the end of the file. – drescherjm Aug 29 '20 at 19:22
  • I know. But, `while(std::getline(std::cin, line) != std::cin::eof())` ? – John Smith Aug 29 '20 at 19:25
  • 1
    The current code is correct and it will avoid this issue: [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm Aug 29 '20 at 19:27
  • 1
    getline returns false on eof – SuperStormer Aug 29 '20 at 19:27