Error Handling in C programming language

in error-handling •  2 years ago 

In my last blog i shared a program to find a number from a string and we learnt about a new standard C library as well. In the program we created we left a portion that will be modified today.

It was a if statement that was needed to modified so that our program can handle errors and send the desired message to us.

Here is the modified program itself.

Screenshot 2022-12-30 010337.png

You can copy the above code from below :

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

char* endptr;
long num = strtol(str, &endptr, 10);
if (*endptr != '\0')
{
printf("Error: Could not find a number in the string.\n");
}
else
{
printf("The number is: %ld\n", num);
}

return 0;
}

This modified program reads a string from the user using the fgets() function, which reads a line of input from the standard input (in this case, the keyboard). It then uses the strtol() function to try to extract a number from the string. If the string does not contain a number, it prints an error message. Otherwise, it prints the number that was extracted.

For example, if the user enters the string "12345", the program will output the following:

Screenshot 2022-12-28 222141.png

If the user enters the string "Hello, world!", the program will output the following:

Screenshot 2022-12-30 010536.png

So we can see that how a single line of code helped us handle the error very easily. What might looks tough is not always tough.

We just have to think and handle errors in the best way possible.

If you also want to learn coding then find your teacher according to your language. For me i am comfortable with hindi language and follow hindi teachers.

You can refer to my teacher below in case you are also comfortable with hindi.

Source

I will soon call myself a trader and a small programmer together.

Happy trading and keep learning what you love.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!