我想通过printf在C中多次调用相同的字符串

afdcj2ne  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(150)

我正在做哈佛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);

按预期工作!

cvxl0en2

cvxl0en21#

问题是这些数组

char firstname[5] = "Bruce";
char lastname[5] = "Wayne";

不包含字符串。您需要扩大数组以包含字符串字面量的终止零字符'\0',如

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);

相关问题