限制用户输入

Limiting user input

本文关键字:输入 用户      更新时间:2023-10-16

我已经编写了以下代码,并且在很大程度上它做了我想要它做的事情。问题是,当用户输入"111"之类的东西时,输出是"您输入了数字1"。我想将用户的输入限制为1个字符。有什么建议吗?我相信解决办法很简单,但是我想不出来。此外,代码必须保持switch语句的形式。谢谢你!

#include <iostream>
using namespace std;
int main()
{
    char i;
    cout << "Please enter a number between 1 and 9." << endl;
    cout << "Enter a number: ";
    cin >> i;
    switch (i)
        {
        case '1':
            cout << "You entered the number one." << endl;
            break;
        case '2':
            cout << "You entered the number two." << endl;
            break;
        case '3':
            cout << "You entered the number three." << endl;
            break;
        case '4':
            cout << "You entered the number four." << endl;
            break;
        case '5':
            cout << "You entered the number five." << endl;
            break;
        case '6':
            cout << "You entered the number six." << endl;
            break;
        case '7':
            cout << "You entered the number seven." << endl;
            break;
        case '8':
            cout << "You entered the number eight." << endl;
            break;
        case '9':
            cout << "You entered the number nine." << endl;
            break;
        default:
            cout << "You did not enter a valid number." << endl;
            break;
        }
    system("pause");
    return 0;
}

您可以使用c标准io库中的getchar(char)。

    #include <stdio.h>
    ...
    char i;
    int j;
    cout << "Please enter a number between 1 and 9." << endl;
    cout << "Enter a number: ";
    getchar(j);
    i=(char)j;
    switch(i){
    ...

有一种方法很容易:只需将char c切换到int n,并将case '1'替换为case 1等。尝试这样做,直到用户输入一个有效的数字,然后输入"a"(即不是数字的东西)。通常,容易的方式也是错误的方式。;)

现在,你可以用这段代码来代替:

std::string line;
while (getline(std::cin, line))
{
    if (line == "1") {
        std::cout << "You entered the number one." << std::endl;
    } else if (line == "2") {
        // ....
    } else {
        std::cout << "You didn't enter a valid number" << std::endl;
    }         
}

这里的不同之处在于,由于输入是行基的,没有进一步的解释,所以当输入不能被解释为数字时,流状态不会被修改。在与用户交互时,这通常更健壮。如果稍后您希望使用数字,请查看stringstreams或lexical_cast进行转换。

您可以使用getch()从屏幕上获取单个字符,您可以检查它是否为数字,否则再次请求有效输入