下面是一种基于我在 Stroustrup 的《编程:使用 C++ 的原理和实践》的早期章节中阅读的内容以及Duoas 在 cplusplus.com 上提供的答案的方法。它定义了一个函数 ,get_int_between()
允许您执行以下操作:
int my_variable;
get_int_between(my_variable, min, max, prompt, error_msg);
这将提示、验证并存储到 my_variable。
只是为了好玩,我还包含了一个函数,get_int(my_variable, prompt, error_msg)
,它做同样的事情,但允许任何值的整数。
#include <iostream>
#include <sstream> // stringstream
void get_int(int& d, std::string prompt, std::string fail);
void get_int_between(int& d, int min, int max, std::string prompt, std::string fail);
int main()
{
int my_number = 1; // initialize my_number
get_int(my_number, "Please enter an integer: ", "Sorry, that's not an integer.\n");
//Do something, e.g.
std::cout << "You entered: " << my_number << "\n";
get_int_between(my_number, 1, 2, "Choose the game type (1 or 2): ", "Sorry, that's not an integer.\n");
//Do something, e.g.:
std::cout << "Let's play Game " << my_number << "!\n";
return 0;
}
void get_int(int& d, std::string prompt, std::string fail)
{
while(1) {
std::cout << prompt;
std::string str;
std::cin >> str;
std::istringstream ss(str);
int val1;
ss >> val1;
if(!ss.eof()) {
std::cout << fail;
continue;
} else {
d = val1;
break;
}
}
}
void get_int_between(int& d, int min, int max, std::string prompt, std::string fail)
{
while(1) {
get_int(d, prompt, fail);
if(d > max || d < min) {
std::cout << "Sorry, your choice is out of range.\n";
continue;
}
break;
}
}