我的输出显示一些奇怪的符号 [英] My Output has some weird symbols displaying

查看:265
本文介绍了我的输出显示一些奇怪的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为班级编码.编码是关于要求用户键入其姓名,年龄和ID.然后,程序应根据其姓名中的前6个字母,年龄和学生ID中的前两个字母来获取密码.问题是输出中的符号(╠╠╠╠╠╠╠╠╠╠╠╠╠╠)不确定.谁能告诉我为什么它在那里?然后,它应该计算并显示密码的长度.这是代码:

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

}

它看起来像:

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

推荐答案

密码有22个字符

The passcode has 22 characters

但是您为密码分配了10个字符的缓冲区

And yet you allocated a buffer of 10 characters for passcode

passcode[10]

您不是空终止密码.来自 strncpy

You are not null terminating passcode. Note from strncpy

如果source大于num,则不会在目标末尾隐式附加空字符.因此,在这种情况下,目的地不应被视为以null终止的C字符串(这样读取它会溢出).

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

另请注意,该行

x = strlen(passcode);

在初始化之前对密码起作用.这样,它将包含随机位,从而导致x的值定义不明确.您目前不使用x,因此它不会直接影响当前的问题.

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.

这篇关于我的输出显示一些奇怪的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆