Is it possible to enter a signed char into a scanf function

85 Views Asked by At

I'm wondering if it is possible to save a signed char into a scanf function

/* Program to scan in a negative char */
#include <stdio.h>
int main (){
    signed char myChar;/* trying to save a char as a signed value */
    printf("Enter a signed char: ");
    scanf("%c", &myChar ); /*main part of the code to scan in a signed char */
    printf("You entered:  %c \n", myChar); /*returns a signed char*/
    return 0;
}
2

There are 2 best solutions below

0
0___________ On

You need to use different format:

#include <stdio.h>
int main (){
    signed char myChar;
    printf("Enter a signed char: ");
    scanf("%hhd", &myChar ); 
    printf("\nYou entered:  %hhd \n", myChar); 
    return 0;
}

https://godbolt.org/z/f1785qbvK

0
chux - Reinstate Monica On

Is it possible to enter a signed char into a scanf function?

Yes. OP's signed char myChar; scanf("%c", &myChar ); is OK.

More clearly, a user is entering text, and that can successful get saved in a signed char.


Details: You have 2 broad choices for scanf() to read text from the user and saves it into various objects.

Read in a character and save that character code

If you want to read input "0" and save that as the character '0' (e.g. ASCII 48), then use any of the 3 forms below. "%c" expects a matching pointer as either char *, signed char *, or unsigned char **1.

char myChar_plain;
scanf("%c", &myChar_plain ); 

signed char myChar_signed;  // OP like code
scanf("%c", &myChar_signed ); 

unsigned char myChar_unsigned;
scanf("%c", &myChar_unsigned ); 

Read in numeric text and save that text as an integer

If you want to read input like "0", "123", "-123", "+123", " 123", and save as an integer, albeit a small integer, then use any of the 2 forms below.

signed char myChar_signed;
scanf("%hhd", &myChar_signed ); 

unsigned char myChar_unsigned;
scanf("%hhu", &myChar_unsigned ); 

Instead of d and u, code can use b, d, i, o, u, x, X, n for other bases, etc. b with C23.


Good code, in these cases, checks scanf(...) == 1 to see if input and conversion were successful.


*1 A void * is possible too. Yet leave that for later.

If no l length modifier is present, the corresponding argument shall be a pointer to char, signed char, unsigned char, or void that points to storage large enough to accept the sequence. C23dr § 7.23.6.2 12