artmo-CSstudent
artmo-CSstudent

Reputation: 13

(C) Scanf - input gets 0 every time

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);

Upvotes: 1

Views: 1669

Answers (3)

xing
xing

Reputation: 2446

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.

Upvotes: 0

meaning-matters
meaning-matters

Reputation: 22936

%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.)

Upvotes: 1

Weather Vane
Weather Vane

Reputation: 34560

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.

Upvotes: 1

Related Questions