为什么第二个cin.ignore()是必要的? [英] Why is a second cin.ignore() necessary?

查看:125
本文介绍了为什么第二个cin.ignore()是必要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,每当我写一个程序,使用 std :: cin ,如果我想用户按Enter键结束程序,我必须写 std :: cin.ignore()两次以获取所需的行为。例如:

  #include< iostream> 

int main(void)
{
int val = 0;
std :: cout<< 输入整数:;
std :: cin>> val;

std :: cout<< 请按Enter键继续...<< std :: endl;

std :: cin.ignore();
std :: cin.ignore(); //为什么需要这个?
}

我也注意到,当我不使用 cin 用于实际输入,而只是为 ignore()调用结束时,我只需要一个

解决方案

错误:我正在简化实际发生的事情。



第一个用于清除提取运算符(>>)尚未消耗的内容。
第二个等待另一个\\\



这是完全一样的,当我们做一个std :: getline提取后:<$ c $在调用std :: getline()之前需要c> the_stream :: ignore(std :: numeric_limits< streamsize> :: max(),'\\\
');

I've noticed that whenever I write a program that uses std::cin that if I want the user to press Enter to end the program, I have to write std::cin.ignore() twice to obtain the desired behavior. For example:

#include <iostream>

int main(void)
{
    int val = 0;
    std::cout << "Enter an integer: ";
    std::cin >> val;

    std::cout << "Please press Enter to continue..." << std::endl;

    std::cin.ignore();
    std::cin.ignore();  // Why is this one needed?
}

I've also noticed that when I'm not using cin for actual input but rather just for the ignore() call at the end, I only need one.

解决方案

Discl: I'm simplifying what really happens.

The first serves to purge what the extraction operator (>>) hasn't consumed. The second waits for another \n.

It is exactly the same when we do a std::getline after an extraction: a the_stream::ignore(std::numeric_limits<streamsize>::max(), '\n'); is required before the call to std::getline()

这篇关于为什么第二个cin.ignore()是必要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆