1
votes

Each time i set a value in b after a, the value is reset to 0 in a. In other words, as the code goes, no matter what i input in a it will be always 0 after the second scanf function.

EDIT: I need to use b as char type for the essay, for memory efficiency, so i can't set b to int, but i need to input integer in there.

EDIT2: I need to input an integer in b, example for an input:

1

2

from that point if i

printf("%d",a);

i get 0.

unsigned short a;
char b;
scanf("%hu",&a);
scanf("%d",&b);
3
"%d" in scanf() expects a pointer to int. You are passing a pointer to char and invoking Undefined Behaviour. Try int b;.pmg
Is it guaranteed that the integer value is between CHAR_MIN (-127) and CHAR_MAX (127)? Or, to pose a general question: What is the range of the second value you're reading?meaning-matters
The question edit says you want to input an integer value in b. This can only be a single digit in the range 0..9 which then needs an adjustment from its character value (usually ASCII), such as with scanf(" %c", &b); b -= '0';.Weather Vane
@meaning-matters Yes it's guaranteed.artmo-CSstudent
@xing perfect! can you add this comment as an answer so i can accept it?artmo-CSstudent

3 Answers

1
votes

You are using the wrong format specifier with

scanf("%d", &b);

It should be

scanf("%c", &b);

However since there is a previous scanf statement there is a newline still in the buffer, and to filter that out you can use

scanf(" %c", &b);

Most format specifiers automatically filter out leading whitespace but %c and %[] and %n do not.

It is unclear from the mistake whether the format specifier is at fault, or the variable type.

1
votes

%d requires an int:

int b;

Then, you should check the return value of your scanf() calls. Do both calls return 1?

(scanf() returns the number of input items assigned. Because both your calls have one %..., you must return 1 in both cases.)

0
votes

with char b; and scanf("%d",&b);, scanf will write sizeof (int) bytes to b.
This will corrupt other memory.
scanf("%hhd",&b); will only write one byte to b.