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

问题描述 投票:0回答:1

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

按预期工作!

c printf declaration cs50 string-literals
1个回答
6
投票

问题是这些数组

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);
© www.soinside.com 2019 - 2024. All rights reserved.