2

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();
}
8
  • 1
    Error checking? If your program crashes on invalid input, you're simply not validating it enough.
    – Mat
    Feb 13, 2013 at 8:35
  • Can someone give me an example please? I am quite new to the C programming language.
    – Matthew
    Feb 13, 2013 at 8:36
  • 1
    This is not C specific at all. There's probably approx. a quarter bazillion examples of checking return values of functions available on the web.
    – Mat
    Feb 13, 2013 at 8:41
  • @BartFriederichs I posted some code
    – Matthew
    Feb 13, 2013 at 8:49
  • 1
    @Matthew - You need to check the return value of scanf("%d", &x);. Read the manual page.
    – Ed Heal
    Feb 13, 2013 at 8:51

4 Answers 4

3

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");
}
2

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)
2
  • This line is incorrect printf("Number of bytes read %d",ret); It is the number of items in the format string as demonstrated by your output.
    – Ed Heal
    Feb 13, 2013 at 8:59
  • @EdHeal Yup ! wrote in a hurry . Thanks for pointing it out . !
    – rockstar
    Feb 13, 2013 at 9:07
1

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.");
   }
-2

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.

6
  • So 0 is no longer an integer?!
    – Ed Heal
    Feb 13, 2013 at 8:53
  • the -1 is not from me, but atoi is really a bad example Feb 13, 2013 at 8:53
  • @JensGustedt would strtol be better? The point was to use return codes instead of exceptions. Feb 13, 2013 at 8:54
  • @BartFriederichs, sure. strtol has a precise way of telling you when things go wrong. atoi hasn't since 0 is a valid input. Feb 13, 2013 at 8:57
  • @JensGustedt how exactly, I don't see any difference in the docs. It seems to use errno. I updated my answer. Feb 13, 2013 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.