在C++中,getline() 是一个用于从输入流中读取一行文本的函数。它的基本用法如下:
#include#include int main() { std::string line; std::cout << "Enter a line of text: "; std::getline(std::cin, line); std::cout << "You entered: " << line << std::endl; return 0; }
在上面的示例中,getline() 函数将从标准输入流(std::cin)读取一行字符串,并将其存储在名为 line 的字符串变量中。然后,该行文本将被打印出来。
getline() 函数的原型如下:
std::istream& getline(std::istream& is, std::string& str, char delim);
它接受三个参数:
- is:输入流对象,从中读取一行文本。
- str:字符串对象,用于存储读取的文本。
- delim:可选参数,用于指定行终止符的字符。默认情况下,它是 ‘\n’(换行符)。
除了上述用法,getline() 函数还可以与文件流一起使用,从文件中读取一行文本。
例如:
#include
#include
#include
int main() {
std::string line;
std::ifstream file("example.txt");
if (file.is_open()) {
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
}
return 0;
}
在上面的示例中,getline() 函数与 ifstream 文件流一起使用,从名为 example.txt 的文件中逐行读取文本,并将每行文本打印到标准输出流。