- 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;
}