cin.get()和cin>>

cin>>通常只能读取一个单词。cin.get()可以读取固定长度的字符串,含空格等符号。

一、使用cin函数

由于cin通过空格、制表符、换行符来界定字符串的。故cin在获取字符时只读取一个单词长度,对于有空格的字符串其空格后面字符读不了。

例如:读取姓名
#include <iostream>
using namespace std;

int main()
{
const int size=20;
char name[size];
char add[size];
cout<<"enter name:"<<endl;
cin>>name;
cout<<"enter address:"<<endl;
cin>>add;
cout<<"your name is "<<name<<" and your address is "<<add<<endl;
return 0;
}

运行结果:
enter name:
HSING HSU
enter address:
your name is HSING and your address is HSU

该运行结果不是用户所需的结果。故需要用下面的表示方法。

二、使用cin.get()函数
(1)cin.get()函数与cin.getline()函数类似。但cin.get(name,size);读取到行尾后丢弃换行符,因此读取一次后换行符任留在输入队列中。
例:
#include <iostream>
using namespace std;

int main()
{
const int size=20;
char name[size];
char add[size];
cout<<"enter name:"<<endl;
cin.get(name,size);
cout<<"enter address:"<<endl;
cin.get(add,size);
cout<<"your name is "<<name<<" and your address is "<<add<<endl;
return 0;
}

运行结果:
enter name:
HSING HSU
enter address:
your name is HSING HSU and your address is

运行结果不是用户所需要的结果。
注:第二次直接读取的是换行符

(2)
cin.get()修改:在cin.get(name,size);后面加一条语句:
cin.get();该函数可以读取一个字符。将换行符读入。

#include <iostream>
using namespace std;

int main()
{
const int size=20;
char name[size];
char add[size];
cout<<"enter name:"<<endl;
cin.get(name,size);
cin.get();
cout<<"enter address:"<<endl;
cin.get(add,size);
cout<<"your name is "<<name<<" and your address is "<<add<<endl;
return 0;
}

运行结果:
enter name:
HSING HSU
enter address:
WU HAN
your name is HSING HSU and your address is WU HAN

运行正确。

(3)也可以将两个成员函数拼接起来cin.get(name,size).get()
使用.get()接受后面留下的换行符。

#include <iostream>
using namespace std;

int main()
{
const int size=20;
char name[size];
char add[size];
cout<<"enter name"<<endl;
cin.get(name,size).get();
cout<<"enter address:"<<endl;
cin.get(add,size);
cout<<"your name is "<<name<<" and your address is "<<add<<endl;
return 0;
}

运行结果:
enter name:
HSING HSU
enter address:
WU HAN
your name is HSING HSU and your address is WU HAN

运行正确。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值