您对各种形式的 getline 的熟悉程度似乎有些动摇。这里有几个简单的用法供大家参考:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
string filepath = "test.txt"; // name of the text file
string buffer; // buffer to catch data in
string firstLine; // the first line of the file will be put here
ifstream fin;
fin.open(filepath); // Open the file
if(fin.is_open()) // If open succeeded
{
// Capture first line directly from file
getline(fin,firstLine,'\n'); // Capture first line from the file.
cout << firstLine << '\n'; // Prove we got it.
fin.seekg(0,ios_base::beg); // Move input pointer back to the beginning of the file.
// Load file into memory first for faster reads,
// then capture first line from a stringstream instead
getline(fin,buffer,'\x1A'); // Capture entire file into a string buffer
istringstream fullContents(buffer); // Put entire file into a stringstream.
getline(fullContents,firstLine,'\n'); // Capture first line from the stringstream instead of from the file.
cout << firstLine << '\n'; // Prove we got it.
fin.close(); // Close the file
}
return 0;
}
使用以下示例文件:
This is the first line.
This is the second line.
This is the last line.
您将获得以下输出:
This is the first line.
This is the first line.