使用 printf 格式化字符串
在这一步骤中,你将学习如何使用 printf()
在 C 语言中格式化字符串和各种数据类型。printf()
函数提供了强大的字符串格式化功能。
让我们创建一个新文件来演示字符串格式化:
cd ~/project
touch string_formatting.c
输入以下代码以探索不同的格式化选项:
#include <stdio.h>
int main() {
// 基本字符串格式化
char name[] = "Alice";
int age = 30;
float height = 5.8;
// 简单字符串输出
printf("Name: %s\n", name);
// 多变量格式化
printf("Profile: %s is %d years old\n", name, age);
// 浮点数精度格式化
printf("Height: %.1f meters\n", height);
// 宽度和对齐
printf("Name (right-aligned): %10s\n", name);
printf("Name (left-aligned): %-10s\n", name);
// 混合不同的格式说明符
printf("Details: %s, %d years, %.1f meters\n", name, age, height);
return 0;
}
编译并运行程序:
gcc string_formatting.c -o string_formatting
./string_formatting
示例输出:
Name: Alice
Profile: Alice is 30 years old
Height: 5.8 meters
Name (right-aligned): Alice
Name (left-aligned): Alice
Details: Alice, 30 years, 5.8 meters
常见的格式说明符:
%s
: 字符串
%d
: 整数
%f
: 浮点数
%.1f
: 保留一位小数的浮点数
%10s
: 右对齐,宽度为 10 个字符
%-10s
: 左对齐,宽度为 10 个字符
让我们探索更高级的格式化:
#include <stdio.h>
int main() {
// 十六进制和八进制表示
int number = 255;
printf("Decimal: %d\n", number);
printf("Hexadecimal: %x\n", number);
printf("Octal: %o\n", number);
// 使用零填充
printf("Padded number: %05d\n", 42);
return 0;
}
示例输出:
Decimal: 255
Hexadecimal: ff
Octal: 377
Padded number: 00042