0

I can able get input string but I couldn't get input character why?

int main() { char p[20]; printf("enter the string:\n "); scanf("%s",p); printf("the string is %s\n",p); char c; printf ("enter the character:\n "); scanf("%c",c); printf("the char is %c",c); return 0; } output is I'm entering string as hello and I'm not able to give the input for character why? enter the string: the string is hello enter the character: the char is

16th Jul 2020, 2:53 AM
C Lover
11 ответов
+ 2
Actually, in the line where string is read, scanf"%s", &p); There's no need to use 'address-of' operator for <p>. Arrays decay to pointer to an address of its first element when they are passed as function argument. You can safely do this ... scanf("%s", p); The problem of reading a char is because scanf() behaviour which reads until it finds a whitespace (unless appropriate format specifier was used). scanf() leaves the '\n' character (it is one of the whitespace characters) that was read as user press the Enter key to send the input. And when you try to read a character, that '\n' character will be assigned for variable <c> because it's there (in input stream). Your workaround by adding a space before the %c specifier makes scanf() ignores what was left behind in input stream, and reads a character again, of which it will assign to <c>. That way you get the loop to work as expected 👍
16th Jul 2020, 6:30 AM
Ipang
+ 1
Slick I did this way..but it is working I don't know how int main() { char p[20]; printf("enter the string:\n "); scanf("%s",&p); printf("the string is %s\n",p); char c; printf ("enter the character:\n "); scanf(" %c",&c); printf("the char is %c",c); return 0; }
16th Jul 2020, 3:06 AM
C Lover
0
I think this'll help. I had the same problem today https://www.sololearn.com/discuss/2392402/?ref=app
16th Jul 2020, 2:58 AM
Slick
Slick - avatar
0
Slick so scanf can be used only once in program?
16th Jul 2020, 3:00 AM
C Lover
0
You can use it more than once. try adding getchar(); after the call to scanf when the character is entered. If you have trouble with that, format variable c as a %s string instead of a %c character.
16th Jul 2020, 3:05 AM
Slick
Slick - avatar
0
Aahhh in the one you posted first you were missing the "&" before the variable in scanf. This line: scanf("%c", &c);
16th Jul 2020, 3:09 AM
Slick
Slick - avatar
0
I gave now " %c",&c... I gave space before format specifier but how it is working???
16th Jul 2020, 3:10 AM
C Lover
0
The & symbol acceses the memory address of the variable. Thats how they are assigned
16th Jul 2020, 3:13 AM
Slick
Slick - avatar
0
if I give simply c instead of &c this will not access memory?? then how value Is stored
16th Jul 2020, 3:20 AM
C Lover
0
Thats correct! Characters are stored in the input buffer. I recommend putting it through a debugger and following the c variables value
16th Jul 2020, 3:25 AM
Slick
Slick - avatar
0
Use & for taking input
16th Jul 2020, 1:48 PM
Jahanzaib Shahid
Jahanzaib Shahid - avatar