如何限制用户在控制台中写入的内容

how to limit what the user writes in the console

本文关键字:何限制 用户 控制台      更新时间:2023-10-16
如何

限制用户在控制台上键入的内容?

示例:当他尝试写

1234 时没关系,当他尝试写一个字符 (a( 或单词时什么也没发生,它仍然是 1234

所以他只能输入数字

int main (){
int x;
cin>>x; // i want the x to take only numbers
cout<<x;
return 0;
}

您可以读取客户端正在键入的每个字符并正确处理它(根据需要(。例如,如果你只想要整数作为输入,你可以读取它们,如果你的用户向你发送了一个字符,你可以给他发回一条消息,你可以阻止他发送其他输入,或者你可以忽略你不需要的输入。

int main () {
int x;
cin >> x; // i want the x to take only numbers
if(cin.fail()) {
    cout << "Invalid input" << endl; 
}
return 0;
}

您无法控制哪些用户类型。在任何情况下,您都不应依赖用户输入的有效性。最好的方法是将输入作为字符串获取,验证输入,然后将其转换为整数。

// Check if each character entered in a digit
bool isValidString(string & inp)
{
    for (int i = 0; i < inp.size(); i++)
    {
        // Checks whether inp[i] is a decimal digit character.
        if (!isdigit(inp[i]))
        {
            // This is not a digit.
            return false;
        }
    }
    return true;
}

在主函数中:

int main()
{
    string inp;
    cin >> inp;
    int outputIntValue = 0;
    if (isValidString(inp))
    {
        // Converts the valid digits into integer 
        outputIntValue = atoi(inp.c_str());
        printf("Integer value: %dn", outputIntValue );
    }
    else
    {
        printf("Invalid input: %sn", inp.c_str());
    }
    return 0;
}