我的输出有一些奇怪的符号显示

问题描述:

我不得不为我的课程编码。编码是要求用户输入他们的姓名,年龄和身份证。然后程序应该根据名字中的前6个字母,他们的年龄以及学生ID中的前两个字母的密码进行验证。问题是输出中有一个未识别的符号(╠╠╠╠╠╠╠╠╠╠╠╠╠╠)。谁能告诉我为什么它在那里?然后它应该计算并显示密码的长度。下面是代码:我的输出有一些奇怪的符号显示

#include <stdio.h> 
#include <string.h> 
void main(void) 
{ 
char name[20], id[9], age[3], passcode[10]; 
int x; 


puts("Enter your name:\n"); 
gets(name); 

puts("\nEnter your student id:\n"); 
gets(id); 

puts("\nEnter your age:\n"); 
gets(age); 

x = strlen(passcode); 

strncpy(passcode, name, 6); 
strncat(passcode, id, 2); 

printf("The passcode is:%s \n",passcode); 
printf("The passcode has %d characters..\n",x); 

} 

它看起来像:

Enter your name: 

johnny 

Enter your student id: 

dc87671 

Enter your age: 

20 
The passcode is:johnny╠╠╠╠╠╠╠╠╠╠╠╠╠╠20dc 
The passcode has 22 characters.. 
Press any key to continue . . . 
+0

你不应该使用gets从stdin中读取一个字符串。使用像fgets()或getline() –

的密码有22个字符

;但你可以分配10个字符缓冲区密码

passcode[10] 

您不是null终止密码。来自strncpy的注解

如果source长于num,则不会在目的地末尾附加任何空字符。因此,在这种情况下,目标不应被视为空终止的C字符串(因为它会溢出)。

还要注意行

x = strlen(passcode); 

作用于密码被初始化之前。因此,它将包含随机位,使x的值不能很好地定义。您目前不使用x,因此它不直接影响手头的问题。

+0

这样的函数考虑使用fgets而不是gets,因为它将最大长度作为参数 - http://stackoverflow.com/questions/4346598/gets-function-in-c –

+0

@ ericJ为了让我的代码正常运行,我做了什么? – NewBie

+0

所以编辑我的代码后:这里是 – NewBie