C++ 输入函数getline(cin,str) 与cin.getline(str,int)区别

本文介绍了C++中cin.getline()与getline()函数的区别及其用法。cin.getline()用于处理字符数组,getline()则用于string类型。文章通过示例代码展示了两种方法的使用,并特别指出getline()在读取后会留下结束符,需要额外处理。

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

1.cin.getline()函数是处理数组字符串的,其原型为cin.getline(char * , int),第一个参数为一个char指针,第二个参数为数组字符串长度。

2.getline(cin,str)函数是处理string类的函数。第二个参数为string类型的变量。

前者cin.getline(char,20)表示函数getline是istream类的一个类方法,cin是一个istream对象。

后者getline(cin,str)说明:getline不是类方法。将cin作为参数,指出到哪里去查找输入。


实例:

#include <iostream>
#include <string>
using namespace std;
const int SIZE=20;

int main()
{
	string str;
	cout<<"string method:"<<endl;
	getline(cin,str);
	cout<<"the string is:"<<endl;
	cout<<str<<endl;

	cin.get();//接受最后一个结束符

	char chs[SIZE];
	cout<<"char * method:"<<endl;
	cin.getline(chs,20);
	cout<<"the string is:"<<endl;
	cout<<chs<<endl;

	return 0;
}

运行结果:

string method:
Hello String

the string is:
Hello String
char * method:
Hello Char *
the string is:
Hello Char *

注:getline(cin,str);处理后还留有结束符在输入流中,故需要使用cin.get();//接受最后一个结束符,才能接受后面得输入值。


原文:http://blog.youkuaiyun.com/xumengxing/article/details/6664436

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值