Error checking Integer division by zero

0

I am writing a base conversion program in C++ console and I am using argv[1] and argv[2] for entering the number & base.

     #include "stdafx.h"
    #include <iostream>
 #include <cstdlib>
  #include <time.h>
 #include <math.h>
 #include <errno.h> 
 using namespace std;
const double MAXRANGE = pow(2.0,16.0); // 65536
 const double MINRANGE = -pow(2.0,16.0);

  int main(int argc, char *argv[])
{ 

int result;

if(atof (argv[1]) > 65536)
 { 
cout << "R" << endl;
return 0;
   }

   if(atof (argv[1]) < -65536)
    { 
 cout << "R" << end;
 return 0;
    }


    if(atof (argv[2]) > 65536 || (atof(argv[2]) < -65536))
   { 
cout << "R" << endl;
return 0;
     }


    int no,base,i;
   no=atoi(argv[1]);
   base=atoi(argv[2]);


      if (argc == 3 )
        {
   if(argv[2][0]=='b' && argv[2][1]=='2')
   {  
       cout<<"V"<<endl;

        return 0;
         }

       i= no % base;
        no=no/base;
        cout<<i;

                }

           return (0); 
             }

and I got the error which is

Unhandled exception at 0x012851BE in lab1.exe: 0xC0000094: Integer division by zero.

I understand this error is coming up because I have make condition with zero.But I am not sure, the sure thing is that i don't know how to do error checking now. I have also tried another code

            if(strcmp("b2",argv[2]==0 || strcmp("b3",argv[2]==0)

but it still come up with the same error.

So, How can I do error checking for argv[2] base numbers? The user have to input argv[2] which is base, and I want to check the argv[2] must be 'b1','b2', 'b3' etc.. to 'b16'.

thank you!

c++
visual-c++
arguments
asked on Stack Overflow Apr 5, 2014 by Cin Sb Sangpi • edited Apr 5, 2014 by Cin Sb Sangpi

1 Answer

0

You should check base against zero prior to the corresponding division or throwm catch and handle your zero division exception, i.e.:

if (!base) {
    ...
    // or early return depending on your use case
} else {
   i = no % base;
   no=no/base;
}

or:

   try {
       ...
       if (!base)
           throw std::overflow_error("Divide by zero exception");
       i = no % base;
       no=no/base;
   } catch (std::overflow_error e) {
      ...
   }
answered on Stack Overflow Apr 5, 2014 by lpapp • edited Apr 6, 2014 by lpapp

User contributions licensed under CC BY-SA 3.0