簡體   English   中英

使用“ cin”的用戶輸入驗證

[英]User input validation using “cin”

我需要通過cin驗證用戶輸入,我的代碼如下:

#include"iostream"
using namespace std;

int main()
{
int choice = 0; 
while(1)
{
    cout<<"ENTER your choice a value between 0 to 2"<<endl;
        cin>>choice;    

        // Here i need some logic which will work like "choice" can be only
        // Integer and within the range i.e. 0 to 2 and if it is not
    // satisfy condition then ask user to input again
    switch(choice)
    {
    case 0:
        exit(1);
        break;

    case 1:
       fun();
       break;
    case 2:
       fun1();
       break;
    default: cout<<"Please enter a valid value"<<endl;
            break;
    }
}

return 0;

}

一個簡單的示例:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

template <typename T>
bool toNumber(const std::string &x, T &num)
{
    return (std::stringstream(x) >> num);
}
int main() {
    while (true) {
        cout << "ENTER your choice a value between 0 to 2" << endl;

        string s;
        cin >> s;

        int choice = 0;

        if (toNumber(s, choice)) {
            switch (choice) {
              case 0: exit(1); break;
              case 1: fun();   break;
              case 2: fun1();  break;
            }
        }
        else
            cout << "Please enter a valid value" << endl;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM