如何限制用户在控制台中写入的内容
how to limit what the user writes in the console
如何
限制用户在控制台上键入的内容?
示例:当他尝试写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;
}
相关文章:
- 当用户超过按钮点击限制时报告
- 限制用户可以在 QFileDialog 中选择的文件数量
- 如何为用户设置仅输入 4 位代码的限制?
- C 链接的列表用户输入限制验证导致程序结束
- 如何在 C++ 中限制用户在字符串(动态字符数组)中输入 8 个字符
- 如何限制用户在控制台中写入的内容
- 如何限制用户仅在C++中输入单个字符
- 使用STL并行算法对用户有哪些限制?
- 限制用户输入C
- 如何限制用户只能选择某些驱动器
- GCC C++11 对用户定义的常量和模板参数包的限制
- C 11:列表限制如何在用户定义的对象中分配值
- 如何在本地组策略对象中为特定用户应用软件限制策略
- 在使用cin.get()时C++,我怎么能不限制用户可以输入的字符数
- 限制用户只能在C++中输入实数
- 限制用户输入的字符数
- 限制用户输入某些字符
- 限制用户输入
- Qt5.5 32位连接到MySQL数据库-限制用户帐户
- 限制用户输入