Home > Back-end >  Difference between \r and \n in depth
Difference between \r and \n in depth

Time:09-07

Here is my code to count the number of characters of a given string(i.e use of strlen() function)

#include <stdio.h>
#include<string.h>
#define N 30
int main()
{
   char input[N];
   gets(input);
   int j=strlen(input);
   printf("using library fnc strlen=%d",j);
   int i=0,sum=0;
  for(i=0;input[i]!='\0';i  )
  {
      sum=sum i;
    
  }
    printf("\rusing loop %d",sum);
}

On CODEBLOCKS(GCC compiler) result shows like this

abcdef78
using loop 4y fnc strlen=8
Process returned 0 (0x0)   execution time : 5.816 s
Press any key to continue.

But the online compiler of Programiz shows like this

/tmp/rzNX0Zm3SF.o
abcdef78
using library fnc strlen=8
using loop 8

But after I have changed the code \r by \n ,like this

#include <stdio.h>
#include<string.h>
#define N 30
int main()
{
   char input[N];
   gets(input);
   int j=strlen(input);
   printf("using library fnc strlen=%d",j);
   int i=0,sum=0;
  for(i=0;input[i]!='\0';i  )
  {
      sum=sum 1;

  }
    printf("\nusing loop %d",sum);
}

the code works fine everywhere(CODEBLOCKS too) what up with this \r and \n?

CodePudding user response:

Your first code has

for(i=0;input[i]!='\0';i  ) {
   sum = sum   i;
}

and your second code has

for(i=0;input[i]!='\0';i  ) {
   sum = sum   1;
}

i.e. for a five-character string, the first computes 0 1 2 3 4, while the second computes 1 1 1 1 1.

Beyond that, \r just returns the cursor to the start of the line, while \n advances to the next line.

IOW, printing foo\rbar would only show bar because you're printing foo, rewinding to the start of the line and overwriting it with bar.

CodePudding user response:

  • \r (carriage return) returns the cursor to the first symbol on the line. This is actually something computers inherited from typewriters, the carriage being the mechanical part that moved as you typed.

  • \n (line feed) moves to the next line which may also implicitly involve a carriage return. Also, on a lot of common systems, \n "flushes" the stdout buffer, meaning that the symbols that your program has prepared to print will actually get printed.

For these reasons you should make it a habit of ending your printf lines with \n. It moves on to the next line but also likely ensures that the text gets printed in the order you expect.

  •  Tags:  
  • c
  • Related