getline函数和get函数的区别

1.用get函数读入一个字符

(1)无参数的get函数

cin.get()				//从指定输入流中提取一个字符

(2)由1个参数的get函数

cin.get(c)					//从指定输入流中读取一个字符,赋值给字符变量c

(3)由3个参数的get函数

cin.get(/*字符数组*/str,/*字符个数*/n,/*终止字符*/'/')	//从指定输入流中读取n-1个字符,赋给str,若在读取n-1个字符前遇到指定的终止字符,则提前结束读取

2.用getline函数读入一行字符

cin.getline(/*字符数组*/str,/*字符个数*/n,/*终止字符*/'/')		//从输入流中读取一行字符,用法与带3个参数的get函数类似,但有细微差异

3.getline函数与get函数的区别

使用get函数提取输入流中的字符时,遇到终止字符,可以理解为读取指针停在终止字符前,且终止字符仍保留在输入序列,第二次调用get函数,如果终止字符没变,那么相当于第二个get函数直接遇到终止字符,直接进入下一行程序;如果第二个get函数的终止字符更改,那么输出的第二个get函数返回值将先输出第一个终止字符。

如下:

前后两个get函数终止字符相同

#include<iostream>
using namespace std;
int main()
{
	int ch;
	char a[20];
	cout << "Please enter a sentence:";
	cin.get(a, 20, '/');
	cout << "The first sentence is:" << a << endl;
	ch = cin.peek();
	cout << "The next character(ASCII code) is:" << ch << endl;	//观察到的字符是“/”的ASCII码,而不是空格字符的ASCII码
	cout << "Please enter next sentence:";
	cin.get(a, 20, '/');		//直接跳过了第二个get函数
	cout << " The second sentence is:" << a << endl;
	return 0;
}

前后两个get函数终止字符不同

#include<iostream>
using namespace std;
int main()
{
	int ch;
	char a[20];
	cout << "Please enter a sentence:";
	cin.get(a, 20, '/');
	cout << "The first sentence is:" << a << endl;
	ch = cin.peek();
	cout << "The next character(ASCII code) is:" << ch << endl;	//观察到的字符是“/”的ASCII码,而不是空格字符的ASCII码
	cout << "Please enter next sentence:";
	cin.get(a, 20, '\\');		//输出将包含第一个get函数的终止字符
	cout << " The second sentence is:" << a << endl;
	return 0;
}

 getline函数读取输入流中的字符,遇到终止字符后将丢弃终止字符,因此终止字符不会留在输入序列,第二次调用getline函数是不会跳过,程序如下:

#include<iostream>
using namespace std;
int main()
{
	int ch;
	char a[20];
	cout << "Please enter a sentence:";
	cin.getline(a, 20, '/');
	cout << "The first sentence is:" << a << endl;
	ch = cin.peek();		//观察到的是‘I’的ASCII码
	cout << "The next character(ASCII code) is:" << ch << endl;
	cout << "Please enter next sentence:";
	cin.getline(a, 20, '/');
	cout << " The second sentence is:" << a << endl;
	return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值