我正在做哈佛 CS50,在 C 的第二节课上,讲师说 %s 会自动连续打印每个额外的参数。
好的,这很酷。但是如果我想多次打印第一个字符串怎么办?
#include <stdio.h>
int main(void) {
char firstname[5] = "Bruce";
char lastname[5] = "Wayne";
printf("Hi, %s!\nI am your virtual butler. I will call you Master %s from now on.\nWelcome to %s Manor!", firstname, lastname);
}
然而,它输出:
Hi, BruceWayne!
I am your virtual butler. I will call you Master Wayne from now on.
Welcome to q��U Manor!
代替:
Hi, Bruce!
I am your virtual butler. I will call you Master Wayne from now on.
Welcome to Wayne Manor!
我尝试在谷歌上搜索,但没有找到相关信息来自行解决问题。
更新#1:
根据建议,我进行了更改。
#include <stdio.h>
int main(void) {
char firstname[] = "Bruce";
char lastname[] = "Wayne";
printf("Hi, %s!\nI am your virtual butler. I will call you Master %s from now on.\nWelcome to %s Manor!", firstname, lastname);
}
它输出:
Hi, Bruce!
I am your virtual butler. I will call you Master Wayne from now on.
Welcome to ���(V Manor!
韦恩庄园还是有问题
更新#2
printf("Hi, %s!\nI am your virtual butler. I will call you Master %s from now on.\nWelcome to %s Manor!", firstname, lastname, lastname);
按预期工作!
问题是这些数组
char firstname[5] = "Bruce";
char lastname[5] = "Wayne";
不包含字符串。您需要扩大数组以包含字符串文字的终止零字符 ' ',例如
char firstname[6] = "Bruce";
char lastname[6] = "Wayne";
或者允许编译器自己计算数组的大小,例如
char firstname[] = "Bruce";
char lastname[] = "Wayne";
另一个问题是格式字符串包含三个转换说明符
s
但您只提供了两个相应的参数
printf("Hi, %s\nI am your virtual butler. I will call you Master %s from now on.\nWelcome to %s Manor!", firstname, lastname);
你需要再写一个参数
printf("Hi, %s\nI am your virtual butler. I will call you Master "
"%s from now on.\nWelcome to %s Manor!",
firstname, lastname, lastname);