I\'m trying to use this code to read values between 0 to 255 (unsigned char).
#include
int main(void)
{
unsigned char value;
For pre C99 I would consider writing an extra function for this just alone to avoid that segmentation fault due to undefined behaviour of scanf.
Approach:
#include
int my_scanf_to_uchar(unsigned char *puchar)
{
int retval;
unsigned int uiTemp;
retval = scanf("%u", &uiTemp);
if (retval == 1)
{
if (uiTemp < 256) {
*puchar = uiTemp;
}
else {
retval = 0; //maybe better something like EINVAL
}
}
return retval;
}
Then replace scanf("%u", with my_scanf_to_uchar(
Hope this is not off topic as I still used scanf and not another function like getchar :)
Another approach (without extra function)
if (scanf("%u", &uiTemp) == 1 && uiTemp < 256) { value = uitemp; }
else {/* Do something for conversion error */}