c - 在 C 中打印未知字符,而不是破折号和空格

标签 c pointers char

以下是我的代码的相关部分:

//helper function that prints "------" lines or "      " lines
void li(char*  a, int len)
{
   int i;
      for (i=0; i<len; i++)
        {
          printf("%c",a);
        }
}

//helper function that prints out bar 
void bar(int length, int height)
{
     int i;
//prints out top line
     li("-", length);

//prints middle lines of spaces and "|"
     for (i=0;i<height-2;i++) {
     printf("\n");
     li(" ", 6);
     printf("|");
     li(" ", length-2);
     printf("|");
}
//prints bottom line
     if (height>=2){
     printf("\n");
     li(" ", 6);
     li("-", length);}
  return ;
}

预期输出:

The: ------------
     |          |
     ------------

实际输出

The: ��������������
     ������|�������������|
     ���������������������

^^那些应该是未知字符。

无论如何,我已经尝试解决这个问题,但到目前为止还没有成功。到底发生了什么导致这种情况发生?

最佳答案

问题出在你理解字符和字符串的方式上。 要解决该问题,您可以更改 li() 的签名。定义应该类似于

void li(char  a, int len)
{
   int i;
      for (i=0; i<len; i++)
        {
          printf("%c",a);
        }
}

并且在调用函数 li() 时使用单引号而不是双引号。 li("-", length); 应该是 li('-', length); 等等。 我进行了更改并运行您的代码。虽然它没有按照您的预期打印字符,但至少没有打印不可打印的字符。 这是代码和输出。

//helper function that prints "------" lines or "      " lines
void li(char  a, int len)
{
   int i;
      for (i=0; i<len; i++)
        {
          printf("%c",a);
        }
}

//helper function that prints out bar 
void bar(int length, int height)
{
     int i;
//prints out top line
     li('-', length);

//prints middle lines of spaces and "|"
     for (i=0;i<height-2;i++) {
     printf("\n");
     li(' ', 6);
     printf("|");
     li(' ', length-2);
     printf("|");
}
//prints bottom line
     if (height>=2){
     printf("\n");
     li(' ', 6);
     li('-', length);}
  return ;
}
main()
{
bar(5,5);
li('G',5);

}

输出:

-----
      |   |
      |   |
      |   |
      -----GGGGG

您可以更改代码,使其按照您想要的方式打印。 希望这会有所帮助。

关于c - 在 C 中打印未知字符,而不是破折号和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13152021/

相关文章:

c++ - 虚指针的大小-C++

c - 请解释d [2] [3]处的值

C - 为什么在进行指针运算时转换为 uintptr_t 与 char*

检查我对特定角色的内存 - 做不到

c - 在不使用多态性的情况下优化 C 代码大小

c++ - 从 malloc() 进行的 Windows 和 Linux native 操作系统/系统调用是什么?

c - 如何将内存分配应用于计数列表中单词数量的C程序? (例如,malloc,calloc,免费)

c++ - 指针数组无法解释的行为(带有浅拷贝)c++

c++ - 将 unsigned char* 缓冲区分配给字符串

java - 无法正确计算字符数