C++ 在使用cin请求int时,如何有效地防止用户输入?

C++ 在使用cin请求int时,如何有效地防止用户输入?,c++,visual-c++,cin,C++,Visual C++,Cin,这是我在这里的第一篇文章,我对编程/C++非常陌生(实际上,在这个兔子洞里只呆了几周)。我在Microsoft Visual Studio 2017中有一个测试项目,我正在尝试找出如何在使用cin时完全避免用户输入。如果我要一个int,而我只想要一个1或0,我希望绝对没有办法让某人在像2或n这样的地方,或者在像“n1”这样的错误和正确的响应之间放置一个空格。目前,我已经到了这样一个地步,我似乎可以创建一个不想要的结果的唯一方法是,如果我先输入一个正确的整数(0或1),然后再输入一个空格和任何其他

这是我在这里的第一篇文章,我对编程/C++非常陌生(实际上,在这个兔子洞里只呆了几周)。我在Microsoft Visual Studio 2017中有一个测试项目,我正在尝试找出如何在使用cin时完全避免用户输入。如果我要一个int,而我只想要一个1或0,我希望绝对没有办法让某人在像2或n这样的地方,或者在像“n1”这样的错误和正确的响应之间放置一个空格。目前,我已经到了这样一个地步,我似乎可以创建一个不想要的结果的唯一方法是,如果我先输入一个正确的整数(0或1),然后再输入一个空格和任何其他字符,并且这个模式可以在初始正确的整数(0 a 42 f 9130)之后再输入无限数量的空格和字符等等。除了用更混乱的代码获得所需的结果之外,我想知道我是否缺少了一些我还没有听说过的内置函数,这些函数可以使这个过程更加高效。以下是我为达到这一点所写的内容:

#include <iostream>
#include <string>
#include <climits>

using namespace std;

int trap;
int wrongNumber();

int numOnly() {
    while (cin.fail())
    {
        // Using someone else's code for this while statement to figure out how to not take a char input when using an int
        // Update: Turned this into a function to be called on whenever cin has a chance to fail because users don't listen.

        cin.clear(); // clear input buffer to restore cin to a usable state
        cin.ignore(INT_MAX, '\n'); // ignore last input
        system("CLS");
        cout << "----------------------------------" << endl;
        cout << "|  You can only enter a number.  |" << endl;
        cout << "| Would you like to pick a card? |" << endl;
        cout << "|  Type 1 for yes or 0 for no!   |" << endl;
        cout << "----------------------------------" << endl;
        cin >> trap;
    }
    if (trap != 1 && trap != 0) {
        system("CLS");
        wrongNumber();
    }
    return trap;
}

int wrongNumber() {

    // At least I made this fail-safe on my own!

    while (trap != 1 && trap != 0) {
        system("CLS");
        cout << "----------------------------------" << endl;
        cout << "|    That is not a 1 or a 0!     |" << endl;
        cout << "| Would you like to pick a card? |" << endl;
        cout << "|   Type 1 for yes or 0 for no!  |" << endl;
        cout << "----------------------------------" << endl;
        cin >> trap;
    }
    if (cin.fail()) {
        system("CLS");
        numOnly();
    }
    return trap;
}

int main() {

    cout << "----------------------------------" << endl;
    cout << "| Would you like to pick a card? |" << endl;
    cout << "|   Type 1 for yes or 0 for no!  |" << endl;
    cout << "----------------------------------" << endl;
    cin >> trap;

    while (cin.fail())
    {
        numOnly();
    }

    if (trap != 1 && trap != 0) {
        wrongNumber();
    }
#包括
#包括
#包括
使用名称空间std;
int陷阱;
int错误编号();
国际货币基金组织{
while(cin.fail())
{
//在这个while语句中使用其他人的代码,以了解如何在使用int时不接受char输入
//更新:把它变成了一个函数,当cin因为用户不听而有可能失败时,就可以调用它。
cin.clear();//清除输入缓冲区以将cin恢复到可用状态
cin.ignore(INT_MAX,'\n');//忽略最后的输入
系统(“CLS”);

cout在不依赖某些操作系统功能的情况下,最好的方法是:

#include <iostream>
#include <limits> // std::numeric_limits
#include <cctype> // std::isspace

// function to read and discard whitespace except '\n' from a stream
std::istream& eat_whitespace(std::istream &is)
{
    char ch;

    // as long as the next character in the stream is a space and not a newline
    while (std::isspace(ch = is.peek()) && ch != '\n') 
        is.get(); // get and discard the character

    return is;
}

int read_range_strict(std::istream &is, int min, int max)
{
    int value;

    // as long as
    while (!(is >> value >> eat_whitespace) // extraction of an int fails
           || is.peek() != '\n' // or the next character in the stream is not a newline *)
           || value < min || max < value // or the value is not within the specified range
    ) {

        std::cerr << "Please enter a number between " << min << " and " << max << "!\n\n";
        is.clear(); // clear flags
        // discard everything that might be left in the stream
        is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    return value;
}

int main()
{
    int value;
    do {
        value = read_range_strict(std::cin, 0, 1);
    } while (true); // only for demo
}
#包括
#包括//标准::数值限制
#include//std::isspace
//函数从流中读取并丢弃除“\n”以外的空白
std::istream&eat_空格(std::istream&is)
{
char ch;
//只要流中的下一个字符是空格而不是换行符
while(std::isspace(ch=is.peek())&&ch!='\n')
is.get();//获取并丢弃字符
回报是;
}
整数读取范围严格(标准::istream&is,整数最小值,整数最大值)
{
int值;
//只要
而(!(is>>value>>eat_whitespace)//提取int失败
||is.peek()!='\n'//或者流中的下一个字符不是换行符*)
||值<最小值|最大值<值//或该值不在指定范围内
) {

std::cerr因为唯一有效的值是0和1,所以不需要将输入作为int读取。只需将其作为字符串读取,修剪任何空白,并将字符串与“0”或“1”进行比较


当然,您也可以只接受“y”或“n”,这会更方便用户使用。

作为答案状态之一,将输入读入字符串,然后对该字符串求值更容易。以下是一个示例:

#include <iostream>
#include <string>

int main() {
  std::string trap;

  std::cout << "Enter 1 or 0" << std::endl;
  std::getline(std::cin, trap); // fetch user input, save into trap
  while (std::cin.fail() || (trap != "1" && trap != "0")) {
    std::cout << "That was not a 1 or 0; try again" << std::endl;
    std::getline(std::cin, trap);
  }
  return 0;
}
#包括
#包括
int main(){
串陷阱;

std::cout根据编译器的不同,您可以使用诸如getch()之类的C代码,并在完成检查后将其回显到屏幕上。然后您必须逐个字符地获取代码,并显然地组装字符串


并非所有的C++编译器都支持这个。这是C++代码,而不是C++。< /P> < P>我建议你不要用一个整数来存储一个“是”或“否”的答案,使用一个字符串代替。这样你就可以保存一些代码,代码为<代码> CIN。
intmain(){
圈闭;
您真的无法阻止某人使用
std::cin
输入无效输入。但是,您可以将输入读入
std::string
,然后在用户输入任何内容后对其进行验证。如果不是“1”或“0”,请打印错误并再次询问。否则,您可能需要签出或以其他方式获取输入。
 int main() {

    string trap;
    cout << "----------------------------------" << endl;
    cout << "| Would you like to pick a card? |" << endl;
    cout << "|   Type 1 for yes or 0 for no!  |" << endl;
    cout << "----------------------------------" << endl;
        cin>>trap;

        while (trap != "1" && trap != "0") { //You can make this while block into a function if you prefer
            cout << "----------------------------------" << endl;
            cout << "|    That is not a 1 or a 0!     |" << endl;
            cout << "| Would you like to pick a card? |" << endl;
            cout << "|   Type 1 for yes or 0 for no!  |" << endl;
            cout << "----------------------------------" << endl;
                cin>>trap;
        }
    return 0;
}