How to achieve right alignment in C language?
In C language, right alignment can be achieved using the formatting output of the printf function. The specific steps are as follows:
- Define a variable to represent the number or string to be output.
- When using the printf function, use the “%nd” in the formatted output, where n represents the width of the output.
- If the length of the output number or string is less than n, it will automatically be padded with empty spaces before being displayed to align to the right.
Here is an example code to create a right-aligned number output.
#include <stdio.h>
int main() {
int number = 1234;
int width = 8; // 输出的宽度为8
printf("%*d\n", width, number);
return 0;
}
The above code will generate the following output:
1234
In this case, the number 1234 is outputted with right alignment and padded with 3 empty spaces in front.