在 C++ 中,getline 函数主要有两种常用的形式,分别是 <iostream> 头文件中的 std::getline 用于从输入流读取一行字符串,以及 <cstdio> 头文件中的 std::getline(C++11 引入)用于从文件流读取一行。下面分别介绍它们的参数:
1. std::getline 用于标准输入流或其他输入流
这个 getline 函数定义在 <iostream> 头文件中,用于从输入流中读取一行文本。它有两个重载版本:
版本一:
cpp
#include <iostream>
#include <string>
std::istream& getline (std::istream& is, std::string& str);
-
参数说明:
is:一个输入流对象的引用,通常是std::cin用于标准输入,也可以是文件输入流std::ifstream等。该函数会从这个输入流中读取数据。str:一个std::string对象的引用,用于存储从输入流中读取的一行文本。读取的内容会被追加到这个字符串中。
-
返回值 :返回输入流对象
is的引用,这样可以方便进行链式调用。
示例代码:
cpp
#include <iostream>
#include <string>
int main() {
std::string line;
std::cout << "请输入一行文本: ";
std::getline(std::cin, line);
std::cout << "你输入的文本是: " << line << std::endl;
return 0;
}
版本二:
cpp
#include <iostream>
#include <string>
std::istream& getline (std::istream& is, std::string& str, char delim);
-
参数说明:
is:同版本一,是一个输入流对象的引用,用于读取数据。str:同版本一,是一个std::string对象的引用,用于存储读取的内容。delim:一个字符,作为分隔符。函数会从输入流中读取字符,直到遇到该分隔符为止,读取的内容(不包括分隔符)会被存储到str中。默认情况下,分隔符是换行符'\n'。
-
返回值 :返回输入流对象
is的引用。
示例代码:
cpp
#include <iostream>
#include <string>
int main() {
std::string line;
std::cout << "请输入以逗号分隔的文本: ";
std::getline(std::cin, line, ',');
std::cout << "读取到的内容是: " << line << std::endl;
return 0;
}
2. std::getline 用于文件流(C++11 引入)
这个 getline 函数定义在 <cstdio> 头文件中,用于从文件流中读取一行文本。
cpp
#include <cstdio>
std::size_t getline(char** lineptr, std::size_t* n, std::FILE* stream);
-
参数说明:
lineptr:一个指向字符指针的指针。如果*lineptr为NULL,则函数会使用malloc分配足够的内存来存储读取的行。如果*lineptr已经指向一块分配好的内存,函数会尝试使用这块内存,如果不够则会重新分配。n:一个指向std::size_t类型的指针,用于存储当前分配给*lineptr的内存大小。如果*lineptr为NULL,则*n会被忽略,函数会自动分配内存。stream:一个std::FILE*类型的文件指针,指向要读取的文件流。
-
返回值:返回读取的字符数(不包括终止的空字符),如果到达文件末尾或发生错误,则返回 -1。
示例代码:
cpp
#include <cstdio>
#include <cstdlib>
int main() {
std::FILE* file = std::fopen("test.txt", "r");
if (file == nullptr) {
std::perror("无法打开文件");
return 1;
}
char* line = nullptr;
std::size_t len = 0;
ssize_t read;
while ((read = std::getline(&line, &len, file)) != -1) {
std::printf("读取到 %zd 个字符: %s", read, line);
}
std::free(line);
std::fclose(file);
return 0;
}
以上就是 getline 函数在 C++ 中的不同参数形式和使用方法。