我正在做哈佛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);
按预期工作!
1条答案
按热度按时间cvxl0en21#
问题是这些数组
不包含字符串。您需要扩大数组以包含字符串字面量的终止零字符'\0',如
或者允许编译器自己计算数组的大小,如
另一个问题是,格式字符串包含三个转换说明符
s
,但您只提供了两个相应的参数你需要写多加一个参数