c - 如何在c中打印字符串末尾没有p┐的字符串

标签 c

所以我一直在编写一个程序,将十进制数转换为其 bool 表示形式,但每次我编译返回值(一个字符串)时,都会显示其他字符,例如 p ┐ 这是程序

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main (void)
{
    signed char str[256];
    int dec,rest;
    int i = -1;
    int j;
    printf ("write a decimal number : ");
    scanf ("%d",&dec);
    do
    {   
        rest = dec % 2;
        dec/= 2;
        for (j=i;j>-1;--j)
            str[j+1]=str[j];
        str[0]=rest+48;
        ++i;
    } while (dec!=0);
    printf ("the binary representation of this number is %s",str);
}

输出:

write a decimal number : 156
the binary representation of this number is 10011100p┐

我不知道我是否错过了什么,但如果你们帮助我,我将不胜感激

最佳答案

在 C 和 C++ 中,字符串以 null 结尾,这意味着每个有效字符串必须以代码 0 的字符结尾。该字符告诉每个处理该字符串的函数它实际上已经结束。

在您的程序中,您创建一个字符串,signed char str[256];,它最初填充有随机数据;这意味着你保留了256个字符的空间,它们都是垃圾,但系统不知道它们是无效的。尝试打印这个字符串,看看会发生什么。

为了真正告诉系统您的字符串在 8 个字符后结束,第 9 个字符必须是 NUL 字符,或者只是 0。在您的代码中,您可以通过两种方式执行此操作:

  • 在循环之后,赋值str[i] = 0,或者(更简单)
  • 将字符串初始化为signed char str[256]={0};,这会创建存储并用空值填充它;写入字符串后,您可以确定最后写入的字符后面将是 NUL。

关于c - 如何在c中打印字符串末尾没有p┐的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44672462/

相关文章:

c++ - 无法使用 cygwin 运行 cmake

c - 给char指针赋值,但是说Access violation writing location

c - If 链表中的语句未按预期工作

python - SWIG 中的预处理器宏

c - 销毁完整链表(C编程)

c - "#define for if (false) {} else for"的可能用途是什么?

c - cdecl 调用约定为什么调用者必须清除堆栈?

c# - 如何使用 pinvoke 编码另一个传递给 C DLL 的结构

python - 添加到 C 代码的函数和无法识别的 swig 接口(interface); "no attribute ' set_latency'”

c# - C# AccessViolation/Marshalling 中的 native C-DLL