-1
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile("hey.txt");

  myfile >> line;
  cout << line;
  system("pause");
  return 0;
}

Why does this not print out what is in my "hey.txt" file?

user2464737
  • 39
  • 1
  • 1
  • 2

1 Answers1

6

This should do the job, If you are new to these things please read http://www.cplusplus.com/doc/tutorial/files/

EDIT: in article above .good() is a bad practice, look here if you need to more detail Testing stream.good() or !stream.eof() reads last line twice

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {

    while(getline(myfile, line)) {
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
Community
  • 1
  • 1
varun
  • 4,522
  • 33
  • 28
  • 2
    You copy-and-pasted some bad example code. That `while (myfile.good())` loop is a [bad practice](http://stackoverflow.com/questions/4324441/testing-stream-good-or-stream-eof-reads-last-line-twice). – Blastfurnace Jun 07 '13 at 19:46
  • @Blastfurnace I agree, I'll add the link – varun Jun 07 '13 at 19:49
  • Instead of `else cout << "Unable to open file";`, is there a way to throw a FileNotFoundException? I'm newbie in C++. – VansFannel Jul 24 '21 at 08:12