C++中cin、cin.get()、cin.getline()、getline()函数的用法

  • 1.cin :cin可以连续从键盘读取想要的数据,以空格、tab 或换行作为分隔符
#include <iostream>
using namespace std;
int main() 
{  
	//输入5 6 输出11
	int a, b;
	cin >> a >> b;
	cout << a + b << endl;
	//输入asdf 输出asdf
	//输入as df 输出as
	string str;
	cin >> str;
	cout << str << endl;
	system("pause");
	return 0;
}
  • 2.cin.get() :cin.get()可以读取空格
#include <iostream>
using namespace std;
int main() 
{  
	//法-:cin.get(字符变量名)可以用来接收字符
	//无论输入多少,在ch中仅保存了第一个输入的字符
	char ch; 
	ch=cin.get();//或者cin.get(ch); 
	cout<<ch<<endl;
	
	//法二:cin.get(字符数组名,接收字符数目)用来接收一行字符串
	//输入:asdfeg
	//输出:asdf
	char ch2[5];
	cin.get(ch2, 5);
	cout << ch2 << endl;//只接收4个字符,第5个的内容是'\0'
	
	/*法三:cin.get(无参数)没有参数主要是用于舍弃输入流中的不需要的字符,
或者舍弃回车,弥补cin.get(字符数组名,接收字符数目)的不足*/
	string a;
	cin>>a;
	cout<<a<<endl;
	/*此时的第一个cin.get()获取的是cin中最后的'\n',也就是消除缓冲区的'\n'第二个的作用在于在程序结束时输入一个字符,
让程序停留在运行界面*/
	cin.get();
	cin.get();
	system("pause");
	return 0;
}
  • 3、cin.getline() :接受一个字符串,可以接收空格并输出。cin.getline()实际上有三个参数,当第三个参数省略时,系统默认为’\0’
#include <iostream>
using namespace std;
int main() 
{  
	char ch[5];
	cin.getline(ch, 5);
	//cin.getline(ch, 5,'s'); 
	//输入:asd
	//输出:a
	cout << ch << endl;
	system("pause");
	return 0;
}
  • 4、getline() :接受一个字符串,可以接收空格并输出,需包含“ #include< string >“
#include <iostream>
#include<string>
using namespace std;
int main() 
{  
	string s;
	getline(cin, s);
	cout << s << endl;
	//输入:I Love You
	//输出:I Love You
	system("pause");
	return 0;
}
  • 5、gets() :接受一个字符串,可以接收空格并输出,需包含“#include< string >”
#include <iostream>
#include<string>
using namespace std;
int main() 
{  
	string s;
	getline(cin, s);
	cout << s << endl;
	//输入:I Love You
	//输出:I Love You
	system("pause");
	return 0;
}
  • cin.getline()、cin.get()的区别:
    cin.getline()与cin.get()都能接收输入的带有空格的字符串直到遇到换行符停止接收。
    但是二者稍有区别:cin.getline()丢弃换行符,而cin.get()将其保留在输入队列中。
#include <iostream>
using namespace std;

int main() {
	char str[10];
	cin.get(str, 10); 
	cout << "cin.get():" << str << endl;
	
	cin.getline(str, 10);
	cout << "cin.getline():" << str << endl;
	return 0;
}

结果:
在这里插入图片描述

#include <iostream>
using namespace std;

int main() {
	char str[10];
	cin.getline(str, 10);
	cout << "cin.getline():" << str << endl;

	cin.get(str, 10); 
	cout << "cin.get():" << str << endl;
	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值