getline() 是 C++ 标准库中的一个函数,用于从输入流中读取一行文本,并将其存储为字符串。它可以从标准输入、文件流、字符串流等不同类型的输入流中读取数据。
函数签名:
std::istream& getline(std::istream& is, std::string& str, char delim);
参数说明:
- is:输入流对象,可以是
std::cin
(标准输入)、文件流对象(std::ifstream
)、字符串流对象(std::istringstream
)等等。- str:存储读取到的一行文本的字符串。
- delim:分隔符,表示在哪个字符处停止读取,默认为换行符
'\n'
。
返回值:
- 返回输入流对象的引用,通常是
is
,表示函数成功执行。
使用示例:
1.从标准输入中读取一行:
#include <iostream>
#include <string>
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;
}
2. 从文件中读取一行:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string line;
if (file.is_open()) {
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
} else {
std::cout << "Unable to open file." << std::endl;
}
return 0;
}
3. 从字符串流中读取一行:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream ss("Hello World!\nThis is a new line.");
std::string line;
while (std::getline(ss, line)) {
std::cout << line << std::endl;
}
return 0;
}
注意:在每次调用
getline()
函数后,输入流的指针会自动移动到下一行的开头(如果是默认的分割符'\n'),准备读取下一行文本。