2015-02-09 38 views
0

虽然我试图验证用户输入,但我已经尝试过两种编译器,我要么发生两件事情之一。它会: - 不询问用户输入 或 - 等待用户输入,如果输入不正确,将不断循环错误消息。虽然循环意味着不断循环验证用户输入

下面是代码:

cout << "Input number of the equation you want to use (1,2,3): " ; 
cin >> userInput; 
cout << endl; 

while (userInput <= 0 || userInput >= 4) 
{ 
    cout << "Please enter a correct input (1,2,3): " ; 
    cin >> userInput; 
    cout << endl; 
} 

if (userInput == 1) 
{ 

userInput被声明为一个整数。有没有更简单的方法来验证用户输入,或者需要一个while循环?我对编码还很陌生。

+1

似乎直截了当的我,我没有看到一个问题。 – CoryKramer 2015-02-09 16:01:58

+1

可能的重复https://stackoverflow.com/questions/5864540/infinite-loop-with-cin – sashoalm 2015-02-09 16:58:10

回答

2

在使用int userInput似乎直线前进,它当用户输入非数字值失败。您可以使用std::string,而不是和检查,如果它包含一个数值

std::string userInput; 
int value; 
std::cout << "Input number of the equation you want to use (1,2,3): " ; 
while (std::cin >> userInput) { 
    std::istringstream s(userInput); 
    s >> value; 
    if (value >= 1 && value <= 3) 
     break; 

    std::cout << "Please enter a correct input (1,2,3): " ; 
} 

std::istringstream类似于其他输入流。它提供来自内部存储器缓冲区的输入,在这种情况下,由userInput提供的值。

+0

这看起来不错,因为它会检查任何值,而不仅仅是整数。如果可以,你可以评估istringstream和“s”是什么吗?我想我会这样做,但我想知道那些命令,因为我不熟悉它们 – 2015-02-09 16:32:28

0

我会添加一个额外的检查以确保如果用户输入非整数输入,则在尝试下一次读取之前清除流。

cout << "Input number of the equation you want to use (1,2,3): " ; 
cin >> userInput; 
cout << endl; 

while (userInput <= 0 || userInput >= 4) 
{ 
    if (!cin.good()) 
    { 
     cin.clear(); 
     cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    } 

    cout << "Please enter a correct input (1,2,3): " ; 
    cin >> userInput; 
    cout << endl; 
} 
+0

R Sahu:你能解释一下你的意思吗?这是为了防止程序无限循环,如果用户输入一个字符,而不是一个整数,或者是一种清理类的东西? ....我很困惑,对不起,如果我不明白:我不熟悉cin.good,明确或忽略 – 2015-02-09 16:14:59

+0

第一个。不要对不起。当你不回答问题或答案时,寻求澄清对于有效沟通至关重要。 – 2015-02-09 16:17:33

0

,而不是让你有更少的重复行

int userInput = 0; 
do 
{ 
    cout << "Input number of the equation you want to use (1,2,3): " ; 
    cin >> userInput; 
    cout << endl; 
    if (!cin.good()) 
    { 
     cin.clear(); 
     cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    } 
} while (userInput <= 0 || userInput >= 4); 
0

你不想CIN >> INT,如果你执行任何错误检查,我建议使用一个do循环。如果用户输入一个非整数,则最终会遇到难以恢复的情况。

相反,CIN成一个字符串,执行任何错误检查你想和字符串转换为整数:

long x; 
    string sx; 
    cin >> sx; 

    x = strtol(sx.c_str(), NULL, 10); 
+0

如果我将cin更改为字符串,我将如何验证用户输入?我需要一段时间(用户输入不是1,2,3)还是这个问题?我不知道该怎么做 – 2015-02-09 16:20:04