如何检查用户CIN输入是太少还是太多
how to check if the user CIN input are too little or too much?
这可能是一个简单的问题,仅供我自己参考。
我要求用户有2个输入。
当用户按下回车键或用户输入了超过3个输入时,C++控制台如何知道用户缺少1个输入?
谢谢你的回答。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
using namespace std;
int main()
{
char hord;
int x;
char userInput[256] ;
int value;
cout<<"Please enter a ./Even mode number: ";
cin >> hord >> userInput;
if(hord == 'd')
{
value = atoi(userInput);
cout <<"Selected Base 10" << endl;
if (value % 2) /*or *///(x & 1)
printf("%d is an odd number dn", value);
else
{
printf("%d is an even number dn", value);
}
}
else if(hord =='h')
{
sscanf_s(userInput, "%x", &x);
if (x % 2)
{/*or *///(x & 1)
printf("%d is an odd number h n", x);
}
else
{
printf("%d is an even number hn", x);
}
}
else
{
printf("Incorrect mode given ");
}
cin.get();
_getch();
return 0;
}
不要让用户在一行上输入两个值,而是提示用户输入每个值。
std::cout << "Enter the first value and press ENTER: ";
std::cin >> value1;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "Enter second value and press ENTER: ";
std::cin >> value2;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
这将确保用户知道他必须输入两个值,并且您知道您将有两个值。对ignore
的调用是跳过用户在值之后写入的可能的垃圾数据。
您还应该验证用户是否给了您有效的值,如果没有,请再次向用户询问值。
如果这对您不起作用(因为应用程序实际上是面向用户的),那么您应该使用getline()并自己分离输入。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 错误:字符数组的初始值设定项太多
- 对象实例化调用构造函数的次数太多
- Levenshtein 两个文件的距离花费了太多时间
- 我有三个 getline,但是一旦编译,输入就太多了
- 将使用太多的纹理插值器 - 带旋转的着色器
- C/C++:socket() 创建在循环中失败,打开的文件太多
- 使用Visual Studio在虚幻引擎中创建一个新的类c ++给了我太多的错误
- C++:数组<>初始值设定项太多
- GLib-ERROR:为GWakeup创建管道:打开的文件太多
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 一行输入到多个变量
- 我会导致太多内存泄漏,以至于我的计算机无响应吗?
- ZeroMq:打开的文件太多.在同一对象上连续增长的fd使用数
- 读取串行命令花费太多时间
- 为什么 Boost unordered_map 在第一次插入时需要太多时间?
- BRK(0) 花费的时间是否太多?
- Valgrind 声称内存释放中的自由空间太多
- 当我输入字符串时,我的菜单重复了太多次
- 如何检查用户CIN输入是太少还是太多