+ 1

Why fgets/gets skipping the 1st input string?

I had to give inputs to two strings value for FERTILIZER and TECHNIQUE. The inputs are COMPOST MANURE and CROP ROTATION. I used fgets. But it's skipping the input of 1st string but it's solved by using scanf() before first fgets. What's happening? And why do we have to use Scanf()? https://code.sololearn.com/cqz32OKKFcmU/?ref=app

1st Feb 2020, 7:24 PM
Tipu Sultan
Tipu Sultan - avatar
3 Respuestas
+ 2
The call to `scanf` left a terminating character in the input string. This is a '\n' character that follows the number read for <year> variable. The first `fgets` call then gets this left over character instead of reading the input for variable <a>. You can change the call to `scanf` as follows: scanf("%d%*c", &y); Or alternatively, without changing the `scanf` format specifier, you can add this line getchar(); After the `scanf` call. This will consume the left over character also.
2nd Feb 2020, 11:32 AM
Ipang
0
The problem is you try to read a integer with fgets. The link below explains. fgets() reads 'a line of text' from a file; scanf() can be used for that but also handles conversions from string to built in numeric types. https://stackoverflow.com/questions/1252132/difference-between-scanf-and-fgets https://www.geeksforgeeks.org/why-to-use-fgets-over-scanf-in-c/ Why do you want to use fgets ? Scanf seems the better option.
1st Feb 2020, 8:49 PM
sneeze
sneeze - avatar
0
Just add a space after the %d in scanf() and freely use gets or fgets. #include <stdio.h> int main() { int y; char a[100], b[100]; printf("Welcome to Organic Farming\n"); printf("Year\n"); scanf("%d ", &y); printf("Fertilizers\n"); gets(a); printf("Technique\n"); gets(b); printf("Organic Farming was introduced in the year %d. It relies on %s and many of it uses %s", y, a, b); return 0; } fgets or gets will work perfectly well. ALWAYS REMEMBER TO LEAVE A SPACE AFTER %d IN scanf.
20th Apr 2021, 12:49 AM
Tusiime Innocent Boub
Tusiime Innocent Boub - avatar