[原创]cin、cin.get()、cin.getline()、getline()、gets()、getchar()的区别

这几个输入函数经常搞不清具体特点和用法,这里稍作总结

一、cin>>

1、最基本用法,输入一个变量值

2、输入字符串,遇“空格”、“TAB”、“回车”结束,比如输入“hello world”,输出“hello”

二、cin.get()

1.用来接收字符,比如

char c;

c=cin.get();//或者cin.get(c);

cout<<c;

输入 hello,输出h;

2.cin.get(字符数组名,接收字符数目)用来接收一行字符串,可以接收空格,例如

char a[12]; 
cin.get(a,12); 
cout<<a<<endl; 

输入hello world;输出hello world;

输入hello world!!!;输出hello world(因为包含终结符号)

三、cin.getline()

1.cin.getline(字符数组名,接收字符数目),和cin.get()第二个用法类似,但是看编译器cin.getline()是有三个参数,默认是' ',如果将以上例子写成cin.getline(a,12,'l'),将输出he

2.用于二维数组

char a[2][20]; 
for(int i=0;i<2;i++) 

cin.getline(m[i],20); 
}

for(int j=0;j<3;j++) 
cout<<"m[j]<<endl;

四、getline(),接收字符串,可以包含空格,但是必须#include<string>

string str; 
getline(cin,str); 
cout<<str<<endl; 

五、gets(),接收字符串,可以包含空格,但是必须#include<string>

char a[12]; 
gets(a); 

六、getchar(),接收一个字符,必须#include<string>

char ch;
ch=getchar();   //不能写成getchar(ch);

原文地址:https://www.cnblogs.com/librasun/p/5401261.html