如何抑制 C 语言中的末尾空行打印
在 C 语言中,printf() 函数在输出数据后会自动换行,导致在程序结束时打印一个空行。如果不需要这个空行,可以采取以下方法:
1. 使用 fflush() 函数
fflush() 函数用于刷新缓冲区,将缓冲区中的所有数据立即输出到屏幕。在程序结束前调用 fflush(stdout) 可以抑制末尾空行:
立即学习“C语言免费学习笔记(深入)”;
<code class="c">#include <stdio.h>
int main() {
printf("Hello, world!");
fflush(stdout);
return 0;
}</code>2. 使用 setvbuf() 函数
setvbuf() 函数用于设置流的缓冲方式。将其缓冲方式设置为 _IONBF 可以关闭缓冲,导致数据立即输出:
<code class="c">#include <stdio.h>
int main() {
setvbuf(stdout, NULL, _IONBF, 0);
printf("Hello, world!");
return 0;
}</code>3. 使用
直接在 printf() 函数的格式字符串中使用 会输出一个换行符,然后立即刷新缓冲区,从而抑制末尾空行:
<code class="c">#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}</code> 