I have a function int read_int(const std::string& prompt) which reads a prompt message asking for a numerical value, the function then returns the value. The while loop inside the function will go on until the user enters a correct input in this case a number, if the user provides a non-numerical input the function prompts the user to enter another number. The problem I have is that when I input a non-numerical value it catches the error but the program terminates instead of prompting the user again. Any help to make this program work correctly would be appreciated, thank you.
#include <iostream>
#include <string>
#include <stdexcept>
#include <ios>
#include <limits>
int read_int(const std::string& prompt){
std::cin.exceptions(std::ios_base::failbit); //Throws exception when an input error occurs
int num = 0; // user input
while(true){ //Loops until valid input
try{
std::cout << prompt;
std::cin >> num;
return num;
}
catch(std::ios_base::failure& ex){
std::cerr << "Bad numeric string, try again" << '\n';
std::cin.clear(); //Resets the error flag
std::cin.ignore(std::numeric_limits<int>::max(), '\n'); //Skips current input line
}
}
}
int main() {
std::string message = "Enter a number: ";
read_int(message);
return 0;
}