I would like to ask how can I accept \r\n without changing it to \\r\\n, with fgets.
I want the program to translate the \r\n to a newline character instead of printing it as a string.
Current code:
char buff[1024];
printf("Msg for server: ");
memset(buff, 0, sizeof(buff));
fgets(buff, sizeof(buff), stdin);
printf(buff);
Input:
test\r\ntest2
The output I want:
test
test2
My current output:
test\r\ntest2
                OP is typing in
\ r \ n and wants that changed to a line-feed.
Process the input string looking for a \, the start of an escape sequence.
if (fgets(buff, sizeof buff, stdin)) {
  char *s  = buff;
  while (*s) {
    char ch = *s++; 
    if (ch == '\\') {
      switch (*s++) {
        case 'r': ch = '\r'; break; // or skip printing this character with `continue;`
        case 'n': ch = '\n'; break; 
        case '\\': ch = '\\'; break;  // To print a single \
        default: TBD();  // More code to handle other escape sequences.
      }
    }
    putchar(ch);
  } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With