cin.get() cin.getline() cin.ignore() getline() getchar()函数用法

cin.get():一般用于程序暂停;

#include <iostream>
using namespace std;

int main()
{
    char ch;
    cout << "This program has paused. Press Enter to continue.";
    cin.get(ch);
    cout << "It has paused a second time. Please press Enter again."; 
    ch = cin.get();
    cout << "It has paused a third time. Please press Enter again.";
    cin.get();
    cout << "Thank you! \n";
    return 0;
}

需要注意的是,当cin和cin.get()同时存在时,可能无法暂停程序,例如

int main()
{
    int a;
    cin>>a;
    cin.get();
    return 0;
}

这样是没有任何效果的,原因是cin输入时写入的空行留在了缓存区,被cin.get()读取到了,解决方法就是加上一个cin.ignore():

int main()
{
    int a;
    cin>>a;

    cin.ignore();

    cin.get();
    return 0;
}

如图所示: 

watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAbTBfNjAyMDUwNjI=,size_18,color_FFFFFF,t_70,g_se,x_16

 

 

 

cin.getline():读取一行中指定长度的数据并将它存在指定char数组中:

#include <iostream>
using namespace std;

int main()
{
    const int SIZE = 81;
    char sentence[SIZE];
    cout << "Enter a sentence: ";
    cin.getline (sentence, SIZE);
    cout << "You entered " << sentence << endl;
    return 0;
}

输出结果为:

Enter a sentence: To be, or not to be, that is the question.
You entered To be, or not to be, that is the question.

即cin.getline()会读取空格,知道读到回车为止

 

 

cin.ignore():它的一个常用功能就是用来清除以回车结束的输入缓冲区的内容,消除上一次输入对下一次输入的影响。比如可以这么用:cin.ignore(1024,’\n’),通常把第一个参数设置得足够大,这样实际上总是只有第二个参数’\n’起作用,所以这一句就是把回车(包括回车)之前的所以字符从输入缓冲(流)中清除出去。在cin.get()和getchar()中也提到了它的用法。

 

 

getline():平常使用的cin来读取输入时仍不能满足我们需求,例如读取“Jack Chen”时就无法读取空格后的内容, 所以C++中用getline()来解决这个问题:

#include <iostream>
#include <string> 
using namespace std;

int main()
{
    string name;
    cout << "Please enter your name: ";
    
    getline(cin,name);
    cout << "Hello, " << name << endl;
    
    return 0;
}

输出结果为:

Please enter your name: Jack Chen

Hello, Jack Chen

这样,就能读取含有空格的内容啦!

 

 

getchar():

1、从缓冲区读走一个字符,相当于清除缓冲区 

2、若缓冲区没有数据,即读取一个char型字符

int main()
{
	int i;
	char ch;
	
	i=getchar();
	cout<<i<<endl;
	
	cin.ignore();
	
	ch=getchar();
	cout<<ch<<endl;
	
	return 0; 
} 

输出结果为:

49

1

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值