Question

Is it possible to handle data type mismatch exceptions in C?

In C++ and other higher-level languages, the code is usually surrounded by try...catch. However, since there is no exception handling mechanism in C, how do we handle data type mismatch exceptions?

For instance, let us assume that I have a program that requires the user to enter an integer number. If the user hits an alphabetic character by mistake, the program crashes. How can I take care of this in C?

Here is some sample code:

#include "stdafx.h"

void main()
{
    int x = 0;
    printf("Hello World!\n\n");
    printf("Please enter an integer: ");
    scanf("%d", &x);
    printf("\n");
    printf("The integer entered is %d", x);
    printf("\n\n");
    printf("Press any key to exit!");
    getchar();
    getchar();
}
Was it helpful?

Solution

I am going to assume that you are using scanf to handle input. the program should not crash. You need to read the manual page for scanf and in the section return values it tells you that the function returns the number of items matched. You compare this number with what is expected. If they differ you take the appropriate action.

EDIT

Some code for Matthew and Bart:

int i;

if (scanf("%d", &i) == 1)
{
    printf("You have entered %d\n", i);
}
else
{
    printf("You have entered an invalid number\n");
}

OTHER TIPS

Adding code to what @EdHeal rightly says above . Sample Illustrative code :

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

int num;
int ret;

printf("Enter a number\n");
ret=scanf("%d",&num);
/* For better clarity From the man page 
 Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure */
printf("Number of items assigned %d",ret);
printf("The input number is %d",num);
return (EXIT_SUCCESS);

}

So here for your simplicty see the return value of the scanf statment . Upon success i.e when it reads an integer it returns 1 . In case of strings it reads 0 .

Sample Output a ) Input an integer

Enter a number
68
Number of bytes read 1
The input number is 68
RUN SUCCESSFUL (total time: 2s)

b) Input a string

Enter a number
yiy idfd
Number of bytes read 0
The input number is 2665608
RUN SUCCESSFUL (total time: 4s)

Several options for data input:

You can use scanf as mentioned above, but i also recommend reading man pages about getopt, getoptlong

As for validating you can try regcomp, regexec, regerror, regfree. For example :

   const char* pattern = "^[\\+,-]*[0-9]*$";
   regex_t regex;
   int reti;
   reti = regcomp(&regex, pattern, REG_EXTENDED);
   if(reti){
   printf("error");
   exit(1);
   }
   reti = regexec(&regex, "34567", 0, NULL, 0);
   if(reti == 0) {
   printf("String matches pattern.");
   }

C uses return values and the errno global to indicate if anything went wrong or not. So, in your case, let's assume (since you didn't provide any code), you are using strtol to translate a string into an integer:

 char *s = "1234";
 int number;
 number = strtol(s, NULL, 10);

If number is 0 and errno is set, something went wrong.

All functions in C work in this way. To make your code more robust, read strings instead of numbers and convert them.

In fact, there is a lot to be found on exceptions and return codes. In my opinion, exceptions should be used for stuff that is exceptional. And incorrect data input is not exceptional (it is more a rule actually ;-)), so there should be no exception be thrown when it connect convert. Perhaps this is the reason C# also has a TryParse method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top