Allen He
Allen He

Reputation: 75

How to take character input in an array in C?

char name[2];
scanf("%c",name);
printf("%c",name);

I am just starting to learn C. I'm curious about the above code, what I got from the printf output, is not the same with the character I typed in. Rather the output was some funny looking symbol. Can someone explain this to me?

Upvotes: 5

Views: 56075

Answers (4)

Uri Goren
Uri Goren

Reputation: 13700

Either Read a single char

char name[2];
scanf("%c",name);
printf("%c",name[0]);

Or read a string

char name[2];
scanf("%1s",name);
printf("%s",name);

Upvotes: 3

IP002
IP002

Reputation: 547

You need %s since because name contains 2 elements. %c is used for single character so if you want the user to input something for e.g. "as"(without "") and the program to print it out you need %s.

char name[2];

scanf(" %s", name);
printf("%s",name);

Upvotes: 0

pat
pat

Reputation: 12749

For the %c specifier, scanf needs the address of the location into which the character is to be stored, but printf needs the value of the character, not its address. In C, an array decays into a pointer to the first element of the array when referenced. So, the scanf is being passed the address of the first element of the name array, which is where the character will be stored; however, the printf is also being passed the address, which is wrong. The printf should be like this:

printf("%c", name[0]);

Note that the scanf argument is technically ok, it is a little weird to be passing an array, when a pointer to a single character would suffice. It would be better to declare a single character and pass its address explicitly:

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

On the other hand, if you were trying to read a string instead of a single character, then you should be using %s instead of %c.

Upvotes: 5

ajetias
ajetias

Reputation: 1

if you give your input which contains characters less than or equal to two you will get a correct output just as your input if your input contains characters greater than 3 then it doesn't work

Upvotes: -2

Related Questions