一、基本介绍
c++ getline是一种用于从输入流中获取一行文本的函数。它具有灵活、易用的特点,可以支持多种输入流类型,包括标准输入、文件以及字符串等。该函数可以帮助程序员处理各种数据格式的输入,是c++输入输出中一个使用频率非常高的函数。
二、函数原型与参数
c++ getline函数的原型如下:
istream& getline (istream& is, string& str, char delim);
其中,istream
表示输入流类型,string
表示存储输入文本的字符串变量,delim
表示文本分隔符,通常为换行符,也可以自定义其他分隔符。
三、使用示例
1. 从标准输入中读取一行文本
#include <iostream>
#include <string>
using namespace std;
int main()
{
string line;
getline(cin, line);
cout << "输入的内容为:" << line << endl;
return 0;
}
运行程序后,程序会等待用户输入一行文本,然后把文本存放进line
变量中,并输出到控制台上。
2. 从文件中读取多行文本
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("data.txt");
if (!file.is_open())
{
cout << "文件打开失败!" << endl;
return 1;
}
string line;
while(getline(file, line))
{
cout << line << endl;
}
file.close();
return 0;
}
该程序使用ifstream
类型打开data.txt
文件,并通过getline
函数逐行读取文件内容,并输出到控制台上。
3. 使用分隔符获取单词
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string str, char delim)
{
vector<string> result;
string word;
stringstream ss(str);
while (getline(ss, word, delim))
{
result.push_back(word);
}
return result;
}
int main()
{
string sentence = "hello,world,i,am,your,friend!";
vector<string> words = split(sentence, ',');
cout << "分隔后的单词为:" << endl;
for (auto word : words)
{
cout << word << endl;
}
return 0;
}
该程序使用自定义分隔符逐个获取单词,通过调用split
函数,并将单词存储在vector
容器中,最后输出到控制台上。
四、常见问题
1. 如何避免读取空行?
可以使用getline
函数后判断读取的内容是否为空,如果为空,则说明读取到了空行,可以使用continue
语句继续读取下一行。
string line;
while (getline(file, line))
{
if (line.empty()) continue;
}
2. 如何使用getline函数读取空格?
getline
函数默认以换行符为分隔符,如果需要读取包含空格的文本,可以设置分隔符为空格:
string str;
getline(cin, str, ' ');
这样,就可以读取到包含空格的文本字符串。
3. 如何更改getline函数的默认分隔符?
可以使用istream
类的成员函数getline(char*, streamsize, char)
来更改默认分隔符。例如,下面的示例将把\n
替换为;
符号:
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
char str[] = "A;B;C\nD;E;F\nG;H;I";
char *token;
token = strtok(str, ";");
while (token != NULL) {
cout << token << endl;
token = strtok(NULL, ";");
}
return 0;
}
在该程序中,先使用C函数strtok
将str
分割为token
,其分隔符为分号;
,然后从中筛选需要的信息。