Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting \r\n input C program

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
like image 272
Jerry Avatar asked Dec 30 '22 16:12

Jerry


1 Answers

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);
  } 
like image 102
chux - Reinstate Monica Avatar answered Jan 08 '23 16:01

chux - Reinstate Monica