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

时间:2014-10-24 21:20:37

标签: c

#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

输出的第二行令我困惑。那里为什么还有额外的“足球”? 谢谢。

1 个答案:

答案 0 :(得分:0)

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

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

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

0

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

char game1[8] = '\0';
char game2[5] = 0;
相关问题