cin>> cin.get() cingetline getline 输入简介
1. cin>>
最常用的用法,输入一个数字和输入一个字符:
#inlcude<iostream>
using namespace std;
int main()
{
int a; //输入数字的变量a。
char b; //输入字符的变量b。
cin>>a;
cin>>b;
cout<<a<<endl;
cout<<b<<endl;
return 0;
}
输入:2 a
输出:2 a
注意:>> 是会过滤掉不可见字符(如 空格 回车,TAB 等)
同时当输入字符串是遇到空格 回车,TAB 等都结束
#include<iostream>
using namespace std;
int main()
{
char a[10];
cin>>a;
cout<<a<<endl;
return 0;
}
输入:qwe er //遇空格结束。
输出:qwe
2. cin.get()
输入字符变量是只能接受一个,输入字符串变量是可以输入空格
#include<iostream>
using namespace std;
int main()
{
char a; //输入的字符变量。
a=cin.get();
cout<<a<<endl;
return 0;
}
输入a: asdf
输出a:a
#include<iostream>
using namespace std;
int main()
{
char s[20]; //输入的字符串变量。
cin.get(s,20);
cout<<s<<endl;
return 0;
}
输入:atm ATM
输出: atm ATM
注意:在字符串中如果定义了20个只能输出19个字符加上一个“/0”。其他也一样。
3、cin.getline() // 接受一个字符串,可以接收空格并输出
#include <iostream>
using namespace std;
int main ()
{
char a[20];
cin.getline(a,5);
cout<<a<<endl;
return 0;
}
输出:asdf
输入:asdfdfghdfg
接受5个字符到a中,其中最后一个为'\0',所以只看到4个字符输出;
4、getline() // 接受一个字符串,可以接收空格并输出,要有string头文件
#include<iostream>
#include<string>
using namespace std;
int main ()
{
string str;
getline(cin,str);
cout<<str<<endl;
}
输入:abcde
输出:abcde
输入:hello world!
输出:hello world!