How to read a text file - C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BrucePerry
    New Member
    • Dec 2011
    • 7

    How to read a text file - C++

    This article is the second part of the article I made earlier on how to create a text file.

    In this article you will be learning how to read the text file that we created, I will be teaching you how to put this code with the code we made but if you want to put it into a different project or source file and compile it separately that will work also.

    Now lets start the code:
    You should already have this in your source file:
    Code:
    #include<iostream>
    #include<fstream>
    
    using namespace std;
    
    int main() {
     ofstream Myfile;
      Myfile.open ("test.txt");
      Myfile << "This is a test.";
      Myfile.close();
    
      return 0;
    }
    I did change myfile to Myfile with a capital for this tutorial.

    1-> Made a space under "Myfile.close() ;" to make your code look cleaner and put in:
    Code:
    ifstream myfile;
    ifstream provides an interface to read data from files as input streams.

    2-> Under that open your file.

    Code:
     myfile.open("test.txt");
    3-> Now create a char, we are going to call our char "Output".

    Code:
     char output[100];
    4-> Now create an 'if' statement.

    Code:
    if (myfile.is_open()) {
    
    }
    5-> Inside the 'if' statement output the contents of your text file using the char.

    Code:
     while (!myfile.eof()) {
    
        myfile >> output;
        cout<<output;
     }
    6-> Now, under the if statement close your text file.

    Code:
    myfile.close();
    Your code (If you did the first article also) should look like this:

    Code:
    #include<iostream>
    #include<fstream>
    using namespace std;
    
    int main() {
     ofstream Myfile;
      Myfile.open ("test.txt");
      Myfile << "Hello";
      Myfile.close();
     
     ifstream myfile;
     myfile.open("test.txt");
     char output[100];
     if (myfile.is_open()) {
     while (!myfile.eof()) {
    
        myfile >> output;
        cout<<output;
     }
    }
    myfile.close();
    getchar();
    getchar();
    return 0;
    }
    If I missed anything please comment and tell me.

    If you have any problems or want to know anything feel free to inbox me or email me at: <email address removed>
    Last edited by weaknessforcats; Dec 14 '11, 06:19 AM. Reason: Remove email address
Working...