C++ primer plus笔记整理 04

C/C++输入相关整理

常用的一些输入方法:
1.cin
2.cin.get()
3.cin.getline()
4.getline()
5.getchar()

1.cin

这是最常用的输入,可以同时接收几个多个参数,并且它会自动过滤掉空白字符(Tab,空格,换行….)
这也会使得多出来的输入留在输入流中,它只能截断到需要的对应个数的参数

int a,b;
cin>>a>>b;

cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;

//output:
/*
3 5 6 7 
a = 3
b = 5
*/

如上的6,7留在了输入流中,没被读取到
cin接收一串字符串:和上面的规律一样,遇见空白字符直接截断,到这为止的字符串

char a[20];
cin>>a;
cout<<"a = "<<a<<endl;

//output
/*
hello world
a = hello
*/

2.cin.get()

用来接受单个字符

char ch;
ch = cin.get();      //或cin.get(ch)
cout<<"ch = "<<ch<<endl;

//output
/*
yes
ch = y     //这里可以看出来只接收单个字符
*/

接收指定长度的字符数组
cin.get(字符数组名,指定长度)这个函数遇到换行结束,空格和tab都算一个有效字符

char ch[20];
cin.get(ch,20);
cout<<"ch = "<<ch<<endl;

//output
/*
helloworldhelloworld
ch = helloworldhelloworl          //这里最多接收20-1 == 19个字符,因为有一个'\0'占位符,才算一个字符串
*/

cin.get()这个直接使用可以用来某些情况从输入流中提取一个字符,任意字符包括空白,读到EOF返回结束标识

int c;
cout<<"enter a sentence:"<<endl;
while((c=cin.get())!=EOF)
    cout.put(c);

//output
/*
hello wolrd(ctrl+z结束符)
hello world        //如果不加上ctrl+z就会一直等待输入,因为没读到EOF
*/

3.cin.getline()

接收一个字符串,可以接收空格并输出
这个函数其实和上面写到的带参数的cin.get()类似,这个函数的完整形式是:cin.getline(接受字符串的名字,接受的数目,指定结束字符)
一般我们省略了第三个参数,系统默认是以’\n’为EOF,我们来试着改一下:

char ch[20];
cin.getline(ch,20,'a');
cout<<"ch = "<<ch<<endl;

/*
helloworldhelloworld
ch = helloworldhelloworl
*/
/*
hellosa 
ch = hellos       //第一次是超过数组容量被截断了,第二次是遇见结束符'a'被截断
*/

这里我们发现一个问题:cin.get()也能指定三个参数,那么这和cin.getline()不就一模一样了么?
答案是:它们两唯一的区别是cin.get()会保留最后输入的’\n’在缓存区中,而cin.getline()会抛弃这个’\n’
举个例子:

char name[15];
cin.get(name,15);
cout<<"name = "<<name<<"\n";

char addr[15];
cin.get(addr,15);
cout<<"addr = "<<addr<<"\n";

//这里是两个cin.get(),也就是会把'\n'保留在缓存区,那我们知道name读完之后,cin.get()继续读缓存区,这是看见一个'\n',就直接结束了
/*
hello world
name = hello wolrd
addr = 
*/
//很明显,addr什么只读取到了一个结束符,没读到任何一个有效字符

那么,换成cin.getline()呢?

char name[15];
cin.getline(name,15);
cout<<"name = "<<name<<"\n";

char addr[15];
cin.get(addr,15);
cout<<"addr = "<<addr<<"\n";

/*
hello (enter)
name = hello
world (enter)
addr = world
*/
//这时候因为cin.getline()将输入的enter丢弃了,所以addr能读取到'\n'后的字符,并以enter结束读取

4.getline()

接受一个字符串,可以接收空格并输出,但是它是C风格字符串中的函数,需包含#include

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

/*
hello world
hello world
*/

这个函数和之前的cin.getline()用法也类似,也能指定结束符,但是不能指定长度。
原形如下:
istream& getline ( istream& is, string& str, char delim );

istream& getline ( istream& is, string& str );

5.getchar()和putchar()

这两个函数是C中的字符输入输出函数,getchar()和cin.get()功能一样,都是接收一个单字符
函数原形:
#include

int c;
c = getchar();
putchar(c);
putchar('\n');

/*
hello
h
*/
//只读取和输出单个字符,这两个函数比较简单
//putchar()接受整形,是因为ASCII中的128个字符都能用整形表示,你可以用整数来代表,如65 对应 'A'
//同时,getchar()的返回值是int型,cout一个getchar时候是输出字符在ASCII对应的数字,如c是'A'就输出65

有什么错误还请指出,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值