2017-09-23 67 views
0

我需要的是绝对的方法可以不接受小数或有是不会接受这两个小数和字母如何不接受小数和字母输入

#include <iostream> 
#include <limits> 
#include <cmath> 


using namespace std; 

double checkInput(double pagkain) 
{ 
    do 
    { 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
     if (floor(pagkain) != pagkain || pagkain >= 51) 
     { 
      cout << "Invalid Input, We do not aceept letters or decimals. \nPlease try again: "; 
     } 

    }while (floor(pagkain) != pagkain || (pagkain >50)); 

    return pagkain; 
} 
+0

请不要粘贴你的整个程序,特别是当它确实与你的核心问题无关时。此外,这不是代码评论网站。这是为了提出非常具体的编程问题。 –

+0

@ PaulJ.Lucas谢谢你提醒我,感谢你! –

回答

0

既然你只希望整数功能,将数据类型更改为int而不是double是安全的。

接下来,您可以将它作为字符串读取并验证其正确性。

你可以做这样的事情:

int GetValidInteger(int lowerBound, int upperBound){ 
    string result; 
    while(true){ 
    getline(cin, result); 
    bool valid = true; 
    for(int i = 0; i < result.size(); i++){ 
     if(!isdigit(result[i])){ 
     valid = false; 
     break; 
     } 
    } 
    if(!valid){ 
     cout << "Only integers are accepted. Try again...\n"; 
     continue; 
    } 
    int intResult = stoi(result); 
    // Outside this loop, you know that you have a valid integer. 
    // You can check now for your other constraints. 
    if(intResult < lowerBound || intResult > upperBound) 
     cout << "Input should be between " << lowerBound << " and " << upperBound << ". Try again...\n"; 
    else 
     return intResult; 
    } 
} 

您可以使用该功能在所需范围内得到有效的投入。为了获得在1-5范围内的顺序,你这样做:

int order = GetValidInteger(1,5);

同样,当你想在1-50范围内的输入。

+0

哇!太棒了!这是我一直在寻找的东西:o谢谢你!顺便说一句,我怎么知道stoi? –

+0

不客气!这里有一个参考http://en.cppreference.com/w/cpp/string/basic_string/stol –

相关问题