0

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 . . .
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
NewBie
  • 1
  • 1
  • 3

1 Answers1

3

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.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Consider using fgets instead of gets, because it takes the maximum length as a parameter - http://stackoverflow.com/questions/4346598/gets-function-in-c – Andrew Williamson Jan 21 '16 at 18:19
  • @ericJ so what shoud i do in order to get my code running? – NewBie Jan 21 '16 at 18:24
  • You need to add a null terminator e.g. passcode[6] = '\0' after copying the name. You also need to handle the case where the name is less than 6 digits, e.g. "eric". You might pad a shorter name with spaces, or you might change 6 to be min(strlen(name), 6); – Eric J. Jan 21 '16 at 18:37