0

Why this code does not print value of s2

#include <stdio.h> int main() { char s1[100],s2[100]; int c; fgets(s1,100,stdin); scanf("%d",&c); fgets(s2,100,stdin); puts(s1); printf("%d",c); puts(s2); return 0; }

30th Jan 2020, 11:47 AM
Somvir Dhaka
Somvir Dhaka - avatar
8 Réponses
+ 4
Solution: getchar() after scanf(). After you type the number for c, you press "enter". "enter" means '\n', which is left after scanf(). And the second fgets() immediately stop reading the input after reading the '\n'. So the second input will never be read.
30th Jan 2020, 11:57 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
How your giving the inputs? For ex: If you're giving like Ssss 7 Aaaa Then s1=Ssss, c=7, s2="" \\\nevery thing after 7 until \n If you're giving like: Ssss 7 aaaa Now s1=Ssss, C=7, S2=aaaa
30th Jan 2020, 2:00 PM
Jayakrishna 🇮🇳
+ 1
Yes.. Ssss you can follow as CarrieForle said in first reply.. And I said the same.. Just you need to consume \n after Integer. So alternatively instead of last fgets you can use scanf without worry about enter pressing or not.. Like scanf("%s", s2);
31st Jan 2020, 9:32 AM
Jayakrishna 🇮🇳
0
If we use gets instead of scanf then also problem sustains
30th Jan 2020, 12:02 PM
Somvir Dhaka
Somvir Dhaka - avatar
0
Then suggest solution
30th Jan 2020, 2:19 PM
Somvir Dhaka
Somvir Dhaka - avatar
0
Can you explain more? What else solution you need? What is your program requirements? If you don't need c value to be taken then remove, give 2 lines of input.. Else Take input like: Ssss 7 Aaaa Or else put getchar() after scanf, then you can enter 3 lines of input but press enter after inputting value to C, immediately.....
30th Jan 2020, 2:23 PM
Jayakrishna 🇮🇳
0
I want to take three inputs in different lines and then print
31st Jan 2020, 9:21 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
That's what my solution does.
31st Jan 2020, 9:22 AM
你知道規則,我也是
你知道規則,我也是 - avatar