My Output has some weird symbols displaying

蹲街弑〆低调 提交于 2019-12-25 14:38:12

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/34931221/my-output-has-some-weird-symbols-displaying

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!