I'm getting an unwanted result of division by zero in my code (the code is written in C++):
#include <iostream>
#include <signal.h>
#include <fenv.h>
void div0(int signo, siginfo_t *info, void *ucontext)
{
if(signo == SIGFPE && info->si_code == FPE_FLTDIV)
{
std::cout << "You can't divide numbers by 0, idiot!\n";
exit(EXIT_FAILURE);
}
}
int main()
{
feenableexcept(FE_ALL_EXCEPT);
struct sigaction act;
act.sa_flags = SA_SIGINFO | SA_NODEFER;
act.sa_sigaction = div0;
int retn = sigaction(SIGFPE, &act, NULL);
if(retn == -1)
{
perror("sigaction");
return -1;
}
int n1, n2;
std::cout << "Enter a number: ";
std::cin >> n1;
std::cout << "Enter another number to divide by: ";
std::cin >> n2;
double div = n1 / 1.0 / n2;
std::cout << n1 << " / " << n2 << " = " << div << "\n";
return 0;
}
When I assign the value 0
in the variable n2
, the result is, for example: 5 / 0 = inf
. But I want to get: You can't divide numbers by zero, idiot!
. I used the SIGFPE
signal with the FPE_FLTDIV
signal code, and I tried to change the double
to float
, but it still didn't work. I searched on the Internet and I didn't find any solution. Did I miss something? Thanks for the help.