在 c 语言中,%s 用于格式化字符串,在字符串中插入变量或表达式。语法:printf("%s", str); str 是要插入的字符串变量或表达式。用法包括:打印字符串、打印变量和打印格式化字符串。
%s 在 C 语言中的用法
%s 是 C 语言中格式化字符串的占位符。它用于在字符串中插入变量或表达式。
语法:
printf("%s", str);
其中:
- %s 是格式化说明符,用于插入字符串。
- str 是要插入的字符串变量或表达式。
用法:
- 打印字符串:printf("Hello, world!n");
- 打印变量:int age = 25; printf("My age is %dn", age);
- 打印格式化字符串:printf("This is a %s string.n", "formatted");
示例:
#include <stdio.h>
int main() {
char name[] = "John";
int age = 30;
// 打印字符串
printf("My name is %s.n", name);
// 打印变量
printf("My age is %d.n", age);
// 打印格式化字符串
printf("I am %d years old and my name is %s.n", age, name);
return 0;
}</stdio.h>
输出:
My name is John.
My age is 30.
I am 30 years old and my name is John.
注意:
- %s 只能用于插入字符串。对于其他数据类型,需要使用其他格式化说明符(例如 %d、%f、%c)。
- 插入的字符串必须是有效的 C 字符串(以 '0' 结尾)。