繁体   English   中英

C++不能在cin之后有cin.ignore()?

[英]C++ can't have cin.ignore() after cin?

我在使用 cin.ignore() 时遇到问题,如果我在 cin >> 语句之后使用它,它似乎不起作用并结束程序。 这是我的代码:

#include "stdafx.h"
#include <iostream>
using namespace std;
int number ;
int main () {
    cin >> number;
    cout << number;
    cin.ignore()
    return 0;
}

我在提示符下输入“ 4 ”(不带引号)。 我希望它提示输入一个 int(它确实如此),然后显示该 int,直到用户再次按下 Enter。 但是,只要我在第一个提示下按 Enter 程序就会关闭。 如果我用新的 cin >> 替换 cin.ignore() 然后它会等到我在关闭之前在该提示处输入数据,但是这样我必须将数据放入提示中,我不能只是按 Enter 来关闭它.

我读到在 cin 输入之后放置 cin.clear() ,但这没有帮助。 如果我用 cin >> num2 替换 cin.ignore(); 然后它工作正常。 我究竟做错了什么?

例如,如果您的用户没有输入有效的int类型作为输入,您可以重置您的输入流并忽略它的其余部分。 while循环将不会退出,直到number包含实际整数。 之后,如果您希望程序等到用户按下“Enter”或任何其他键,您可以再次调用ignore

#include <limits>
#include <iostream>    

int main()
{
    int number;
    // we need to enforce that the input can be stored as `int` type
    while(!(std::cin >> number))
    {
        std::cout << "Invalid value! Please enter a number." << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    std::cout << "Your number is: " << number << std::endl;

    // wait for user to press Enter before exiting
    // you can do this with ignore() x2 once for the newline
    // and then again for more user input
    std::cout << "Press Enter to exit." << std::endl;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM