+ 2

How to avoid the extra newline character from being added to a string while using the fgets() in C?

Code: #include <stdio.h> #include <string.h> int main() { char c[10]; fgets(c, 10, stdin); printf("%s and Jerry\n", c); printf("%s is %d characters long", c, strlen(c)); return 0; } Input: Tom Output: Tom and Jerry Tom is 4 characters long Expected Output: Tom and Jerry Tom is 3 characters long Is there a way to obtain the expected output only by using fgets for input? The above code would work fine on Sololearn's code playground when the 'Submit' button is hit after entering only the input. But, when the code is run on a PC you must press the 'Enter'/'Return' button for the computer to accept the input. That is where this issue arises. Any help would be highly appreciated. Thank you.

18th Jun 2024, 7:00 AM
Ashwin Saseendran PC
Ashwin Saseendran PC - avatar
1 Answer
+ 4
You can't avoid it, but you can replace it. To replace '\n' with '\0', you can use strlen this way: ... fgets(c, 10, stdin); c[strlen(c)] = '\0'; //add this to replace '\n' with '\0' printf(... ...
18th Jun 2024, 1:01 PM
Bob_Li
Bob_Li - avatar