While the catch attempt loop fails when cin fails

I can’t understand why this gets into the loop after entering non-int. I tried cin.flush (), which does not seem to exist, cin.clear (), which seems to work, even cin.sync () after reading someone else a message about it, works, but it doesn't seem , has the meaning. Also tried cin.bad ().

Thanks so much for any help

Enter the first number: f Sorry, I do not think the number?

Enter the first number: Sorry, I do not think the number?

Enter the first number: Sorry, I do not think the number?

Enter the first number: Sorry, I do not think the number?

Enter the first number: Sorry, I do not think the number? Sorry, you will not try anymore. Press any key to continue.,.

#include <iostream>
using namespace std;

int main(){
    int entry;
    int attempts = 1;
    int result;
    while(attempts <= 5) {
        try {
            cout << "\n\nPlease enter the first number: ";
            cin >> entry;
            if (cin.fail())
                throw "Sorry, I don't think that a number?";
            if (entry < 0)
                throw "Sorry, no negative numbers. Try something else? ";
            cout << "\nNow the second number: ";
            cin >> entry;
            cin.clear();
            cin.get();
        }
        catch (char* error) {
            cout << error;
            attempts++;
        }
    }
    if (attempts > 5)
        cout << "Sorry, you don\'t get any more tries.\n";
    system("pause");
    return 0;
}
+3
source share
6

, , . .

cin.clear() std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n'); catch. cin.clear() cin, cin.ignore() , .

( , , , ).

+9

( ) - . , (, ) , .

// Infinite loop for retrying until successful
while (true) {
    // Ask the user something
    std::cout << prompt;
    // Read the answer (one full line)
    std::string line;
    if (!std::getline(std::cin, line))
      throw std::runtime_error("End of input while expecting a value");
    // Put the line read into iss for further parsing
    std::istringstream iss(line);
    int val;
    // Read val from iss and verify that reading was successful and
    // that all input was consumed
    if (iss >> val && iss.get() == EOF) return val;
    std::cout << "Invalid input, try again!\n";
}

BASIC:

template <typename Val> void input(std::string const& prompt, Val& val) {
    // (the above code goes here, slightly adjusted)
}

int main() {
    int w;
    double l;
    input("Enter weight in kg: ", w);
    input("Enter length in m: ", l);
    std::cout << "BMI: " << w / (l * l) << std::endl;
}

, :

  • std::string
  • , ,
+3

char cin →

"", cout < , ...

, !

========================================

double fi_trap_d()    // function to return a valid range double catching errors  
{  
  double fi_game_sec;  
//-------------------------------------------  
   do  
   {  
    fi_game_sec = -1;  
    cout << fi_game_sec_c;  

        //------------------------------  
    cin.ignore();  // (1)
        //------------------------------  

    try  
    {  cin >> fi_game_sec;  cin.clear(); }  // (2)
        catch (...)  //out_of_range)  
      {  
        fi_game_sec = -1;  
        cout << " Dis am an error!\n";  
                     // just loop back as we asked for a number  
      }  
    } while (fi_game_sec < 1);  
//-------------------------------------------  
  return fi_game_sec;  
}  

========================================

"Dis am is error!" .

(1) (2)!

+2

, . , - . ( ). ( ) - , . , :

char ch;
int attempts = 0;

std::cout << "Please enter the first number: ";
do { 
    cin >> ch;
    attempts++;
    if (attempts > 5)
        std::cerr << "The only allowable inputs are '0' through '9'\n";            
} while (cin.good() && !isdigit(ch));
int first_number = ch - '0';

, . , , . , / , , , , .

0

? , .

.

-1

, iostream .

cin.exceptions( ios::failbit );

try {
} catch( ios_base::failure & ) {
  cin.clear();
}

, - throw , std::exception, char*.

-1
source

Source: https://habr.com/ru/post/1733418/


All Articles