What is the purpose of the getline function in C++?
In C++, the `getline()` function is used to read a line of text from an input stream (such as standard input or a file) and store it in a string variable. Its purpose is to easily obtain an entire line of input, rather than just a single word or character.
Grammar:
#include <string>getline(cin, str);
cin is the standard input stream object.
str is a string variable used to store the text lines read.
示例:Example
#include <iostream>#include <string>
int main() {
std::string input;
std::cout << "请输入一行文本: ";
std::getline(std::cin, input);
std::cout << "你输入的文本是: " << input << std::endl;
return 0;
}
In the above example, the `getline()` function is used to read a line of text inputted by the user from the standard input stream and store it in a string variable named `input`. The text is then outputted to the console.
It is important to note that the `getline()` function will read the input stream until it encounters a newline character (including the newline character) and remove it from the input stream. Therefore, the next time you read, the `getline()` function will read the next line of text.