How to left align text in C language?
In C language, the common method of left-aligning is achieved through the format specifier of the printf function. The specific method involves using the format “%-ns”, where n is the output field width and s is the string to be output.
Here is a sample code:
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int width = 20; // 输出字段宽度
printf("%-*s\n", width, str);
return 0;
}
The output results are:
Hello, World!
The output string is left-aligned and occupies a specified width. If the length of the string exceeds the specified width, the output will be truncated based on the actual length of the string.