Accepting \r\n input C program

Viewed 489

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
4 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);
  } 

[Edit] I now suspect OP is inputting \ r \ n and not carriage return line feed.

I'll leave the below up for reference.


After fgets(), use strcspn())

if (fgets(buff, sizeof buff, stdin)) {
  buff[strcspn(buff, "\n\r")] = '\0';  // truncate string at the first of \n or \r
  puts(buff);  // Print with an appended \n
}  

You would need to replace de \r\n substring with a newline character:

Live demo

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buff[1024];

    printf("Msg for server: ");
    fgets(buff, sizeof(buff), stdin);

    char *substr = strstr(buff, "\\r\\n"); //finds the substring \r\n

    *substr = '\n'; //places a newline at its beginning

    while(*(++substr + 3) != '\0'){ //copies the rest of the string back 3 spaces 
        *substr = substr[3];   
    } 
    substr[-1] = '\0'; // terminates the string, let's also remove de \n at the end

    puts(buff);
}

Output:

test
test2

This solution will allow you to have other \ characters or "\n" and "\r" separated substrings along the main string, if that's a concern, only that particular substring will be replaced, everything else stays the same.

in your input string, "\r" have two characters : '\' & 'r'. but '\r' is a single character. "\r\n" is a string of 4 byte while "\r\n" is a string of 2 byte.

if you have to do this, write a string replace function before gets

Related