My Output has some weird symbols displaying

2019-09-12 15:23发布

I had to a coding for my class. The coding is about asking the user to type their Name, age and id. An then the program should for a passcode based on the first 6 letter in their name, their age and the first two letter in their student id. The problem is the a unidentified symbol (╠╠╠╠╠╠╠╠╠╠╠╠╠╠ )in the output. Can anyone tell me why it is there>? Then it should calculate and display the lenght of the passcode. Here is the code:

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

}

And it look like:

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 . . .

标签: c strcat strncpy
1条回答
Evening l夕情丶
2楼-- · 2019-09-12 15:54

The passcode has 22 characters

And yet you allocated a buffer of 10 characters for passcode

passcode[10]

You are not null terminating passcode. Note from strncpy

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

Note also that the line

x = strlen(passcode);

is acting on passcode before it is initialized. As such, it will contain random bits, rendering the value of x not well defined. You do not use x currently, so it is not directly affecting the issue at hand.

查看更多
登录 后发表回答