cin.get()和cin>>

xiaoxiao2021-02-28  76

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 HSUenter 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 HSUenter 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 HSUenter address:WU HANyour 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 HSUenter address:WU HANyour name is HSING HSU and your address is WU HAN

运行正确。

转载请注明原文地址: https://www.6miu.com/read-2627944.html

最新回复(0)