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: \n"; if (file2.is_open()) { //check if the file is open while (getline(file2, line)) { cout << line << endl; } file2.close(); }
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"); }
c++ how to read from a file
#include <fstream> #include <iostream> using namespace std; int main() { /* You create a stream using the file in a * similar way to how we use other streams. */ ifstream in; // Open the file in.open("names.txt"); if(in.fail()) cout << "File didn't open"<<endl; int count = 0; string line; while (true) { /* Get line will work as long as there is * a line left. Once there are no lines * remaining it will fail. */ getline(in, line); if (in.fail()) break; /* Process the line here. In this case you are * just counting the lines. */ count ++; } cout << "This file has " << count << " lines." << endl; return 0; }