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.
Open a file using open(filename, mode) as a file with mode “r” and call readline() function on that file object to get the first line of the file.
The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a linefeed. The content of the StringBuffer are then output to the console.
Just echo the first list of your source file into your target file. For which head -n 1 source. txt > target.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With