User Program Communication

Read from Text File in C++

Used to read from a text file.


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

//input stream
ifstream openFile(fileName);
if (openFile.is_open()){ //checking for existence of file
    string stringToStore; //string to store file line
    getLine(openFile, stringToStore); //gets a line from the file
    openFile.close(); //closes file after done
}



Notes

Ifstream is the object created from the file, used for input.
getLine increments the file line automatically on every call.


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

int main(){
    //input stream
    ifstream grades("names_grade.txt");
    if (grades.is_open()){
        string gradeAndName;
        while(getLine(grades, gradeAndName){ 
            cout << gradeAndName << \n;
        }
        grades.close();
    }
}

< Namespaces   |   Write to File >

© 2018 SyntaxDB. All Rights Reserved.