以下是我的代码的相关部分:
//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/