getline from file c++ code example
Example 1: get line C++
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Example 2: getline of file C++
ifstream inFile;
string name;
int age;
inFile.open("file.txt");
getline(inFile, name);
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
Example 3: reading a entire file in C++ getline
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}