14

I am using fstream and C++ and all I want my program to do is to print out to the terminal the contents of my .txt file. It may be simple, but I have looked at many things on the web and I can't find anything that will help me. How can I do this? Here is the code I have so far:

    #include <iostream>
#include <fstream>
using namespace std;

int main() {
    string output;
    ifstream myfile;
    ofstream myfile2;

    string STRING;
    myfile.open ("/Volumes/LFARLEIGH/Lucas.txt");

    myfile2 << "Lucas, It Worked";

        myfile >> STRING;
        cout << STRING << endl;
    myfile.close();


    return 0;
}

Thank you in advance. Please forgive me if this is very simple as I quite new to C++

Lucas Farleigh
  • 448
  • 2
  • 6
  • 15

3 Answers3

30

There's no reason to reinvent the wheel here, when this functionality is already implemented in the standard C++ library.

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream f("file.txt");

    if (f.is_open())
        std::cout << f.rdbuf();
}
Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106
0
#include <iostream>
#include <fstream>

int main()
{
    string name ;
    std::ifstream dataFile("file.txt");
    while (!dataFile.fail() && !dataFile.eof() )
    {
          dataFile >> name ;
          cout << name << endl;
    }
  • 2
    Could you explain your code? Why is it better than the [accepted answer](https://stackoverflow.com/a/35202275/711006)? – Melebius Mar 27 '18 at 17:44
  • While answering, please mention what is wrong in the actual code posted and what is corrected and why it has to be corrected in that way. Below link will help you. https://stackoverflow.com/help/how-to-answer – Prasoon Karunan V Apr 04 '18 at 03:47
0

Try this, just modified at some places. You had tried to open a file using extracter (i.e, ifstream) but overwriting this file using inserter (i.e, ofstream) without opening the file, that ifstream and ofstream were two different classes. so, they don't understand.

#include<iostream>
#include<fstream>

using namespace std;

int main(){

    string output;
    ifstream myfile;
    ofstream myfile2;

    string STRING;
    // output stream || inserting
    myfile2.open ("/Volumes/LFARLEIGH/Lucas.txt");

    myfile2 << "Lucas, It Worked";


    myfile2.close();

    // input stream || extracting

    myfile.open("/Volumes/LFARLEIGH/Lucas.txt");

        myfile >> STRING;
        cout << STRING << endl;
    myfile.close();


   return 0;
}
Velu Vijay
  • 21
  • 1
  • 5