简体   繁体   中英

cannot assign a value to a character variable with scanf in c?

sorry for the somewhat vague title. I am trying to run a simple program where the user inputs one character and it is immediately recalled. So far i have

#include <stdio.h>
int main(){
char ch;
printf("Enter one char\n");
scanf_s("%c", &ch);
printf("the char is %c.\n",ch);
return(0);
}

But for some reason this returns "the char is ." and i have no idea why.

if i change it to

#include <stdio.h>
int main(){
int ch;
printf("Enter one char\n");
scanf_s("%d", &ch);
printf("the char is %d.\n",ch);
return(0);
}

it works fine and returns the integer that I entered so i dont think the problem is with the codes structure. For some reason i just seem to be unable to assign a value to a ch variable. Any help would be greatly appreciated.

Try
scanf_s("%c", &ch, 1);

valter

What you're using is a secured version of scanf and always remember the scanf_s needs the buffer size argument to work so in order to make scanf_s work in your program use this

scanf_s("%c", &ch, 1);

Where 1 is the buffer size argument . HTH :)

EDIT: And one more thing why your program is working when you make it ch as int because scanf_s doesn't need the buffer size argument for integer,floats but whenever you're reading a character, strings, arrays you should mandatorily provide the buffer size argument.

Replace scanf_s() with scanf() as scanf_s() is Microsoft specific. I am having code running fine with scanf().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM