C++ cin.getline和 cin.get用法和区别

cin.getline()

#include <iostream>
#include<iomanip>
#include<string>
using namespace std;
const int Limit = 255;

int main()
{

    char input[Limit];

    cout << "Enter a string for getline() processing:\n";
    cin.getline(input, Limit, '#');         //输入到input数组,遇到#字符终止,从输入流中删除#字符
    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;

    if (ch != '\n')
        cin.ignore(Limit, '\n');            // 清空255个字符直到遇到'\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);    //get保留的#字符    
    cout << "The next input character is " << ch << endl;
    return 0;
}

测试结果:getline()函数丢弃输入中的分界字符#,而get()函数不会
在这里插入图片描述

getline

getline实现带空格的输入

#include <iostream>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
    string ss;
    getline(cin, ss);
    cout << ss;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值