Search code examples
cterminalscanffgets

C When executing C file in terminal, how can I add line break to input when prompted by fgets() or scanf()?


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?


Solution

  • Usually that can't be done with fgets and scanf, but you can use getchar instead:

    int ch;
    int idx = 0;
    while( ( (ch = getchar()) != EOF ) && idx < MAX_BYTES)
    {
        string[idx++] = ch;
    }
    printf("%s", string);
    

    Note getchar will accept any input including \n and the while loop terminates when EOF ie Ctrl+D from stdin. You then copy each character to the buffer accordingly.