64,642
社区成员
发帖
与我相关
我的任务
分享
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str ); <string>
Get line from stream
Extracts characters from is and stores them into str until a delimitation character is found.
The delimiter character is delim for the first function version, and '\n' (newline character) for the second. The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.
Notice that unlike the c-string versions of istream::getline, these string versions are implemented as global functions instead of members of the stream class.
Parameters
is
istream object on which the extraction operation is performed.
str
string object where the extracted content is stored.
delim
The delimiting character. The operation of extracting succesive characters is stopped when this character is read.
Return Value
The same as parameter is.
// getline with strings
#include <iostream>
#include <string>
using namespace std;
int main () {
string str;
cout << "Please enter full name: ";
getline (cin,str);
cout << "Thank you, " << str << ".\n";
}
对于文件来说,
std::ifstream infile("words.txt");
std::ofstream outfile("WordsFile.txt");
std::string line;
if(outfile)
{
std::cout << "Writing out to WordsFile.txt.\n";
for(int i = 0; i < 25; i++)
{
std::getline(infile, line, '\n'); //以'\n'标志结束,
outfile << line;
outfile << '\n';
}
}