What is the use of r in C
×


What is the use of \r in C

39

Introduction to \r in C

In C programming, \r represents a carriage return character.

When encountered in a string, it instructs the output device to move the cursor to the beginning of the current line.

This can be useful for tasks such as updating progress indicators or implementing simple animations in console-based applications.

The \r character in C provides a simple yet effective way to control cursor positioning in console output.

By moving the cursor to the beginning of the line, it enables dynamic updating of progress indicators, animations, or any other text-based visualizations, enhancing the user experience in console-based applications.


Example:

Program 1: Updating Progress Indicator

// Program for \r in C
#include<stdio.h>

int main() {
    int i;
    printf("Progress: ");

    for(i = 0; i <= 100; i += 10) {
        printf("%d%%", i);
        fflush(stdout); // Flush output buffer to ensure immediate display
        sleep(1);       // Simulate work
        printf("\r");   // Move cursor to beginning of line
    }

    printf("\nDone.\n");
    return 0;
}

Output:

Progress: 0%
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%

Done.

The program displays a progress indicator from 0% to 100% with a step of 10%.

After each step, \r moves the cursor to the beginning of the line, allowing the progress to be updated in-place.

fflush(stdout) ensures that the output is immediately displayed without buffering.

sleep(1) simulates work by pausing execution for 1 second.


Program 2: Simple Animation

// program for simple animation 
#include<stdio.h> 

int main() {
    char animation[] = "|/-\\";
    int i;

    for(i = 0; i < 10; i++) {
        printf("\r%c", animation[i % 4]); // Rotate through animation characters
        fflush(stdout);                   // Flush output buffer
        usleep(200000);                   // Pause for 200 milliseconds
    }

    printf("\n");
    return 0;
}

Output:

|
/
-
\
|
/
-
\
|
/

This program creates a simple animation using characters '|', '/', '-', and ''.

\r moves the cursor to the beginning of the line, allowing the animation to overwrite the previous character.

The animation loops through the characters in the animation array.

fflush(stdout) ensures immediate display, and usleep(200000) pauses execution for 200 milliseconds between frames.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments