C++中的字符串输入

对于字符数组的输入可以使用cin.getline(str,len)和cin.get(str,len)这两个方法,注意他们两者的区别
getline()将直接舍弃换行符,而get方法则会遇到换行符结束,换行符仍保留在输入队列中,如果再次调用get方法,则字符数组中会有"\n";

对于字符串类型的输入可以使用getline(cin,str)

程序代码

#include <iostream>
#include <string>
using namespace std;
int main(void){
	char a[10], b[10], c[10];
	string d, e;
	cin.getline(a, 10);
	cin.getline(b, 10);
	cin.get(c, 10);
	getline(cin, d);
	getline(cin, e);
	cout<<a<<endl;
	cout<<b<<endl;
	cout<<c<<endl;
	cout<<d<<endl;
	cout<<e<<endl;
	return 0;
} 

运行截图

在这里插入图片描述
可以发现,d中存储的是换行符,get方法会将换行符保留在输入队列中,getline方法会将换行符舍弃

猜你喜欢

转载自blog.csdn.net/qq_41970098/article/details/87891044