Home > Enterprise >  storing a negative integer in signed char
storing a negative integer in signed char

Time:10-05

I'm trying to get a function that stores integers in char. I need to use char rather than int because I need to use the question mark (?) to terminate my loop. However, I can't seem to make my code work. Here's my work:

    int main() {

      signed char num;
      scanf("%c", &num);
      if (num!='?') {
        printf("%c\n", num);
      }
      return 0;
    }

When I input a negative number (say, -9), I get the output:

-

I tried using the integer print symbol (%d) rather than %c when I was printing the values, as I saw on this question: https://www.quora.com/Can-I-assign-a-negative-number-to-a-char-variable-Why-or-why-not but makes everything I input janky. ie when I input 2, it returns 50.

I was told that signed char should do the thing here, but I'm not sure that's the case now.

Thanks.

CodePudding user response:

You use the wrong format:

it has to be (but you will have to enter 63 instead of ?):

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

or

    char str[6];
    char num;
    fgets(str,5,stdin);
    if (str[0]!='?') {
        if(sscanf(str, "%hhd", &num) == 1)
            printf("%c\n", num);
        else {/* handle scanf error*/}

CodePudding user response:

If you want to scan an integer and at the same time scan a character like ? you need:

int num;
char c;
if (scanf("%d", &num) == 1)
{
    // Okay you got an integer.

    c = num;  // BUT... watch out for over/underflow !!!
}
else if (scanf("%c", &c) == 1)
{
    // Okay you got a char
    if (c == '?')
    {
        // You got your ?
    }
    else
    {
        // Some other char

        // Some kind of error handling... perhaps
        c = 0;
    }
}
else
{
    // Input error that can't be recovered
    exit(1);
}
  • Related