Reputation: 231
ifstream infile;
string read_file_name("test.txt");
infile.open(read_file_name);
string sLine;
while (!infile.eof())
{
getline(infile, sLine);
cout << sLine.data() << endl;
}
infile.close();
This program prints all line in the file, but I want to print only first line.
Upvotes: 10
Views: 69873
Reputation: 45450
while (!infile.eof())
does not work as you expected, eof see one useful link
Minor fix to your code, should work:
ifstream infile("test.txt");
if (infile.good())
{
string sLine;
getline(infile, sLine);
cout << sLine << endl;
}
Upvotes: 20
Reputation: 23
You can try this:
ifstream infile;
string read_file_name("test.txt");
infile.open(read_file_name);
string sLine;
while (!infile.eof())
{
infile >> sLine;
cout << sLine.data() << endl;
}
infile.close();
This should print all the lines in your file, line by line.
Upvotes: 2