punksta
punksta

Reputation: 2818

Cheking of cin result c++

I need to request a size of array, which should be posite number. Look at the function of input and cheking of it.

indexType get_array_size(){
 //indexType - size_t; MAX = max of unsigned int
 long long ansver;
 while(true){
    std:: cout << "Enter size of array{0..." << MAX/2-1 << "} ";
    bool ans = std:: cin >> ansver;
    if(ansver < 0 || !(ans)){
        std:: cout << "Incorect size!" << std::endl;
        ansver = 0;
        continue;
    }
    break;
 }
 return ansver;
}

How it must work: if ansver < 0 or input incorrect(some chars for example) new request, else return obtained value. But in practice only the first request is sent, and then only cout-s "Incorect size" if input was incorrect. Please help. Ps sorry for not good english=)

Upvotes: 1

Views: 115

Answers (1)

R Sahu
R Sahu

Reputation: 206737

When an input stream gets in a bad state, you have to:

  1. Clear the state.
  2. Discard the current input.

before entering new data.

while(true){
    std:: cin >> ansver;

    if (cin.fail()) {
       std::cout << "Bad input!" << std::endl;
       cin.clear(); // unset failbit
       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
       continue;
    }

    if(ansver < 0 ) {
        std::cout << "Incorect size!" << std::endl;
        continue;
    }

    break;
}

Upvotes: 3

Related Questions