[c++复健日常] cin.ignore()

昨天写一个超级无敌基础的题结果栽在输入上, 就是这个

	int i1;
	double d1;
	string s1;
    cin >> i1;
    cin >> d1;
    getline(cin, s1);

然后run的时候发现s1直接被跳过了,单独cout了s1后发现他的值好像变成了\n???一搜才发现好像是getline()把回车键当作我的input了???解决办法就是getline()前面加上一句cin.ignore()

ignore()是input stream下的一个函数,官方文档上它的作用是Extract and discard characters

std::istream::ignore
istream& ignore (streamsize n = 1, int delim = EOF);

Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.
Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.

n是提取的最大字符数, 在之前的问题中, 只需要忽略一个\n, 就使用默认就好了。有时候使用到cin.ignore(numeric_limits<streamsize>::max(),)这样的代码,这就表示流的大小没有上限,提取的字符数没有上限。dim是分隔字符,一旦遇到便停止提取。(EOF:end of file)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值