其他istream类方法(get(),getline(),ignore())

get(char&) 和 get()


简介:

在这里插入图片描述
代码:

#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    /*
    get(char&) 将输入的字符赋给其参数(不会跳过空字符————空格、制表符、换行符)
    */
    char c1, c2, c3;
    cin.get(c1).get(c2).get(c3);
    cout << c1 << c2 << c3 << endl; //可以拼接使用

    /*
    get(void) 将输入字符转换为整型(通常是int)
    注意:get(void)的返回值不是cin,而是int,因此不能拼接使用
    */
    int i;
    i = cin.get();
    cout << i << endl;
    i = cin.get(c1).get(c2).get(c3).get(); //valid get()虽然不能拼接使用,但是它可以放在最后
    cout << c1 << c2 << c3 << i << endl;
    cout << EOF;
    return 0;
}

输出:

ABCDEFGH
ABC
68
EFG72
-1


getline()和get()

  • istream & get(char *, int, char);
  • istream & get(char *, int);
  • istream & getline(char *, int, char);
  • istream & getline(char *, int);

两者的区别:get()将分界字符留在输入队列中,而getline()不保留

代码:

#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    const int Limit = 255;

    char input[Limit];

    cout << "Enter a string for getline() processing:\n";
    cin.getline(input, Limit, '#');
    cout << "Here is your input:\n";
    cout << input << "\nDone with phase 1\n";

    char ch;
    cin.get(ch);
    cout << "The next input character is " << ch << endl;//getline()函数将丢弃输入中的分界字符#

    if (ch != '\n')
        // 读取并丢弃接下来的Limit个字符或直到到达第一个换行符 
        // 默认参数(1,EOF)
        cin.ignore(Limit, '\n'); 

    cout << "Enter a string for get() processing:\n";
    cin.get(input, Limit, '#');
    cout << "Here is your input:\n";
    cout << input << "\nDone with phase 2\n";

    cin.get(ch);
    cout << "The next input character is " << ch << endl;//get()函数不会丢弃输入中的分界字符#

    return 0;
}

输出:

Enter a string for getline() processing:
I am a handsome boy!
you know? #hhhh
Here is your input:
I am a handsome boy!
you know?
Done with phase 1
The next input character is h
Enter a string for get() processing:
I am a handsome boy!
you know? #hhhh
Here is your input:
I am a handsome boy!
you know?
Done with phase 2
The next input character is #

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰茶不冰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值