C++ getline()函数概述

本文深入解析C++中istream::getline的四种重载形式及其应用,通过实例演示如何使用getline从文件中读取文本,直到遇到指定的限定符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其有四种重载形式,分别为:

1. istream& getline (istream& is, string&str, char delime)
2. istream& getline (istream&& is, string&str, char delime)
3. istream& getline (istream& is, string&str)
4. istream& getline (istream&& is, string&str)

 

参数解释:

is:用于文本读取的istream对象。

str:存储从istream中读取的文本的对象。str原有的内容将被丢弃,并替换为读取的文本内容。

delime:限定符,读取到相应的字符将会停止读取。

 

实例:

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

int main() 
{
	using namespace std;
	ifstream fin;
	fin.open("tobuy.txt");
	if (fin.is_open() == false)
	{
		cerr << "Cant't open the file\n";
		exit(EXIT_FAILURE);
	}
	string item;
	int count = 0;
	getline(fin, item, ':');
	while (fin)
	{
		++count;
		cout << count << ": " << item << endl;
		getline(fin, item, ':');
	}
	cout << "Done" << endl;
	fin.close();
	return 0;
}

 

tobuy.txt内容:

 

sardines:chocolate ice cream:

pop corn:olive oil:tofu:

 

 

程序输出:

1: sardines

2: chocolate ice cream

3:

pop corn

4: olive oil

5: tofu

Done

 

参考文献:

1. http://www.cplusplus.com/reference/string/string/getline/ 

2. C++ Primer Plus(第六版)中文版 第16章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值