我试图制作一个用户只能输入0到1的cin。如果用户没有输入这些数字,那么他应该收到错误,说“请输入0到1的范围。”
但它不起作用。
我做错了什么?
int alphaval = -1;
do
{
std::cout << "Enter Alpha between [0, 1]: ";
while (!(std::cin >> alphaval)) // while the input is invalid
{
std::cin.clear(); // clear the fail bit
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid entry
std::cout << "Invalid Entry! Please Enter a valid value: ";
}
}
while (0 > alphaval || 1 < alphaval);
Alpha = alphaval;
答案 0 :(得分:1)
试试这个:
int alphaval;
cout << "Enter a number between 0 and 1: ";
cin >> alphaval;
while (alphaval < 0 || alphaval > 1)
{
cout << "Invalid entry! Please enter a valid value: ";
cin >> alphaval;
}
答案 1 :(得分:1)
如果你想捕获空行我会使用std::getline
,然后解析字符串以查看输入是否有效。
这样的事情:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int alphaval = -1;
for(;;)
{
std::cout << "Enter Alpha between [0, 1]: ";
std::string line;
std::getline(std::cin, line);
if(!line.empty())
{
std::stringstream s(line);
//If an int was parsed, the stream is now empty, and it fits the range break out of the loop.
if(s >> alphaval && s.eof() && (alphaval >= 0 && alphaval <= 1))
{
break;
}
}
std::cout << "Invalid Entry!\n";
}
std::cout << "Alpha = " << alphaval << "\n";
return 0;
}
如果您想要一个不同的错误提示,那么我会将初始提示放在循环之外,并将内部提示更改为您喜欢的内容。
答案 2 :(得分:0)
C ++第一周,从Peggy Fisher's Learning C++ on Lynda.com开始。 这就是我提出的。喜欢收到反馈。
int GetIntFromRange(int lower, int upper){
//variable that we'll assign input to
int input;
//clear any previous inputs so that we don't take anything from previous lines
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//First error catch. If it's not an integer, don't even let it get to bounds control
while(!(cin>>input)) {
cout << "Wrong Input Type. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
//Bounds control
while(input < lower || input > upper) {
cout << "Out of Range. Re-enter option: ";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//Second error catch. If out of range integer was entered, and then a non-integer this second one shall catch it
while(!(cin>>input)) {
cout << "Wrong Input Type. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
//return the cin input
return input;
}
由于练习是为了命令汉堡包,这就是我要求的金额:
int main(){
amount=GetIntFromRange(0,20);
}
答案 3 :(得分:0)
我在寻找一种类似的方法,发现那不错 对照所有不是0或1的东西进行检查。
size_t input;
cout << "Enter Alpha between [0, 1]: ";
do
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << " "Please enter within the range of 0 to 1."
} while((!(cin >> input)) || cin.bad() || input <= 0 || input >= 1);