Search
 
SCRIPT & CODE EXAMPLE
 

CPP

how to open and read text files in c++

// This is how you read a file, and keep it's text in a vector of strings
#include <bits/stdc++.h>
using namespace std;

vector<string> Read_File(string FileName){
    ifstream infile;
    infile.open(FileName);
    vector<string> empty;
    if(infile.fail()){
        cout << "File Could Not Be Reached";
        return empty;
    }
    vector<string> answer;
    while(infile.good()){
        string str;
        infile >> str;
        answer.push_back(str);
    }
    infile.close();
    return answer;
}
int main(){
  vector<string> file_text = Read_File("textfile.txt");
}
Comment

read text from file c++

fstream input;
	input.open("Data.txt", ios::in);
	string city;
	if (input.fail())
	{
		cout << "File does not exist" << endl;
		cout << "Exit program" << endl;
	}

	while (!input.eof()) // Continue if not end of file
	{
		getline(input, city, '.');//getline(file,string,delimit char)
		cout << city << endl;
	}

	input.close();

                            //Another solution

fstream file2;
	file2.open("Data.txt", ios::in);
	string line;
	cout << "Data file: 
";
	if (file2.is_open()) {		//check if the file is open
      
		while (getline(file2, line)) {
			cout << line << endl;
		}
      	file2.close();
	}
Comment

PREVIOUS NEXT
Code Example
Cpp :: how to find length of character array in c++ 
Cpp :: c++ vector sort 
Cpp :: difference between lower and upper bound 
Cpp :: prints out the elements in the array c++ 
Cpp :: change to lowercase in notepad++ 
Cpp :: cases in cpp 
Cpp :: use ::begin(WiFiClient, url) 
Cpp :: how to convert int to std::string 
Cpp :: c++ struct with default values 
Cpp :: c++ string to int conversion 
Cpp :: max value of double c++ 
Cpp :: rand c++ 
Cpp :: print all elements of vector c++ 
Cpp :: how to make copy constructor in c++ 
Cpp :: how to create a min priority queue of pair of int, int 
Cpp :: sieve of eratosthenes algorithm in c++ 
Cpp :: how to store pair in min heap in c++ 
Cpp :: splice string in c++ 
Cpp :: round double to 2 decimal places c++ 
Cpp :: c++ iterate over vector of pointers 
Cpp :: declaring 2d dynamic array c++ 
Cpp :: how to sort a string alphabetically in c++ 
Cpp :: what is c++ standard library 
Cpp :: how to sort in descending order in c++ 
Cpp :: convert letters to uppercase in c++ 
Cpp :: calculate factorial 
Cpp :: reverse function in cpp array 
Cpp :: Program To Calculate Number Power Using Recursion In C++. The power number should always be positive integer. 
Cpp :: setw c++ 
Cpp :: c++ char array size 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =