Scenario 1
char string[MAX_BYTES] = "This is a string\nthat I'm using\nfor scenario 1";
Scenario 2
printf("Enter string: ");
fgets(string, MAX_BYTES, stdin);
If I provide the string in-code (scen. 1), I can line break with '\n'
.
But if prompting in terminal with fgets()
or scanf()
(scen. 2), pressing enter
continues the execution of code.
How can I add a line break to input without triggering the rest of the code?
Usually that can't be done with
fgets
andscanf
, but you can usegetchar
instead:Note
getchar
will accept any input including\n
and thewhile
loop terminates whenEOF
ie Ctrl+D fromstdin
. You then copy each character to the buffer accordingly.