C++ getline()函数概述

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

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章

猜你喜欢

转载自blog.csdn.net/waveleting/article/details/108295028
今日推荐