//想法是,如何将用户限制为这些特定符号? num_1 / 2 iput中的p.s为:10有效asd10无效
do
{
//Input
cout << "Enter first the arithmatic operation (+, -, *, /, %) and then both operands: "; cin >> operation; cin >> num_1; cin>> num_2;
if (cin.fail()) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
} while ( (operation != '+' && operation != '-' && operation != '*' && operation != '/' && operation != '%' )
&& ((num_1 <= '0' || num_1 <= '9') || (num_1 >= 'A' && num_1 <= 'F'))
&& ((num_2 >= '0' && num_2 <= '9') || (num_2 >= 'A' && num_2 <= 'F')) );
答案 0 :(得分:1)
标准库使您几乎无法控制这些东西。
这是个老歌,但是当我需要花哨的输入时,readline仍然是我的首选:
#include <cstdio>
#include <cstdlib>
#include <readline/readline.h>
int snuff_key(int, int) { return 0; }
bool is_key_allowed(char c) {
return (c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'F')
|| (c == '*')
|| (c == '/')
|| (c == '+')
|| (c == '-');
}
int main() {
char* buf;
rl_initialize();
for (unsigned char c = 0; c < 128; c++) {
if (!(is_key_allowed(c))) {
rl_bind_key(c, snuff_key);
}
}
if ((buf = readline("")) != nullptr) {
printf("you typed: '%s'\n", buf);
free(buf);
}
return 0;
}