在 c 中添加到字符串末尾的额外字符 [英] Extra characters added to end of string in c

查看:59
本文介绍了在 c 中添加到字符串末尾的额外字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用 C 打印出一个字符串,当我打印出来时,我一直在字符串的末尾得到额外的字符.代码:

So I am trying to print out a string in C and I am consistently getting extra characters at the end of the string when I print it out. The Code:

char binaryNumber[16] = "1111000011110000";
printf("binary integer: %s\n", binaryNumber);

输出:

二进制整数:1111000011110000▒▒▒▒

binary integer: 1111000011110000▒▒▒▒

你能帮我弄清楚为什么会发生这种情况吗?我认为这是我代码中其他一些问题的根源.我之前在以更复杂的方式创建字符串时遇到过这个问题,并且在这种情况下也有额外的字符,但它们是不同的.所以我以最基本的方式制作了一个字符串(此处显示的方法)并且仍然遇到问题

can you please help me figure out why this is happening. I think this is the root of some other problems in my code. I had this problem before when I was creating the string in a more complex way, and got extra characters in that case too, but they were different. So I made a string the most basic way possible (method shown here) and am still getting the problem

推荐答案

应该是

char binaryNumber[17] = "1111000011110000";

这是因为 C 中的字符串以空字符结尾.因此,如果您不为将添加的隐式 \0 提供额外的字符空间,您将阅读垃圾

This is because strings in C are null terminated. So you will be reading garbage if you don't give an extra character space for the implicit \0 which will be added

这篇关于在 c 中添加到字符串末尾的额外字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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