用于控制字符串输入的异常类?

时间:2015-11-10 13:38:07

标签: c++ exception-handling

如何控制输入在这么长的输入请求中适当且整齐地进行?我正在考虑使用try / catch块,但这似乎是错误/长期的做法。任何提示/指出我正确的道路将非常感激。

    cout << "First Name?: ";
    cin >> first;
    cout << "Last Name?: ";
    cin >> last;
    cout << "Middle Name?: ";
    cin >> middle;
    temp->setName(first, middle, last);
    cout << "ID number? (5 digits): ";
    cin >> ID;
    temp->setId(ID);
    cout << "Age?: ";
    cin >> age;
    temp->setAge(age);
    cout << "Phone number?(ie. ##########): ";
    cin.ignore(); 
    getline(cin, ph);
    temp->setPhone(ph);
    cout << "Address Street Number?: ";
    cin >> addressNum;
    cout << "Address Street Name?: ";
    cin >> addressName;
    temp->setAddress(addressNum, addressName);
    cout << "Gender?: (M or F) ";
    cin >> gender;
    temp->setGender(gender);
    cout << "E-mail?: ";

1 个答案:

答案 0 :(得分:0)

我认为您可以使用do while循环来控制正确的输入。我只显示了身份证号码。

    int flag;
    do
    {
         flag=0;
        cout << "ID number? (5 digits): ";
        cin >> ID;  //as integer type so convert it to string
        string Result;          // string which will contain the result

        ostringstream convert;   // stream used for the conversion

        convert << ID;      // insert the textual representation of 'Number' in the characters in the stream

        Result = convert.str();
        if(Result.length()!=5)// check id exacly 5 digit
        {
          cout<<"Error!\n";
          flag=1;
        }
    } while(flag);
   temp->setId(ID);

您必须包含头文件#include<sstream>