Zsh下程序输出后出现诡异的百分号分析

问题

代码如下

1
2
3
4
5
6
7
#include <stdio.h>
int main(void){
int a;
a = 16;
printf("%d",a);
return 0;
}

输出

1
16%

而当我修改输出语句为

1
printf("%d\t",a);
1
16	%

添加\n后输出正常

1
printf("%d\n",a);
1
16

但是我切换到Bash却没有这个问题,一切按照预期输出

原因

只能说中文搜索引擎还是有点逆天,搜到的全是别人问怎么输出百分号。。

上谷歌搜了一下,找到 Stackoverflow 的一个问答

Getting a weird percent sign in printf output in terminal with C - Stack Overflow

其中有个回答指出

When (non-null) output from a program doesn’t include a trailing newline, zsh adds that color-inverted % to indicate that and moves to the next line before printing the prompt; it’s generally more convenient than bash’s behavior, just starting the command prompt where the output ended.

也就是没加\n时,Zsh会自动给你输出一个百分号然后换行。而bash选择直接是不换行,接着输出。

Author

BakaFT

Posted on

2021-05-24

Updated on

2023-12-28

Licensed under

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×