gpt4 book ai didi

c - 我的程序中的转换字符有什么问题? [初学者]

转载 作者:行者123 更新时间:2023-11-30 17:27:01 26 4
gpt4 key购买 nike

#include<stdlib.h>
#include<stdio.h>
int main()
{
printf("I am the first %s, while I am the second % \n", "substitute", "one");
char game1[9]="Football";
char game2[6]="Chess";
printf("I love %s and %s \n", game1, game2);
}

输出为:

I am the first substitute, while I am the second one
I love Football and ChessFootball

输出的第二行让我感到困惑。为什么那里多了一个“足球”?谢谢。

最佳答案

刚刚检查了您的代码,它对我来说工作正常,您使用什么编译器?您可以通过打印两个字符串的最后一个字符来调试奇怪的行为:

printf("game1 last char: %d\n", game1[8]);
printf("game2 last char: %d\n", game2[5]);

如果这两个值不为 0,那么就会出现问题,因为在读取字符串时,程序会连续读取所有字符,直到遇到空终止符('\0' 作为char 或 0 作为 int)。在这种情况下,编译器可能没有在 char 表中插入尾随空终止符。只需添加(两种方式):

char game1[8] = '\0';
char game2[5] = 0;

如果这两个值实际上都是 0,那么我不知道它可能是什么,但您也可以将字符串初始化为指针:

const char *game1 = "Football";
const char *game2 = "Chess";

关于c - 我的程序中的转换字符有什么问题? [初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26556461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com