| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
- #include <stdio.h>
 
 - #include <string.h>
 
  
- int main(void)
 
 - {
 
 -     char buff[1024] = "\0";
 
  
-     // 指定 buff 为缓冲区,_IOFBF 表示当缓冲区已满时才写入 stdout
 
 -     setvbuf(stdout, buff, _IOFBF, 1024);
 
  
-     fprintf(stdout, "结束时才打印\n");
 
 -   
 
 -     return 0;
 
 - }
 
  复制代码 
 
使用的是C++  .c后缀,在输出时输出乱码。 
尝试复制到vim编译器,可以正确输出。 
不加setvbuf 可以正确输出中文。 
请问这是什么原因呀。
 本帖最后由 人造人 于 2021-2-21 12:45 编辑 
你注释上写了,等缓冲区满了才输出,所以调用fprintf函数的时候不输出 "结束时才打印\n",等结束程序之前才输出,这时main函数已经返回了,局部变量buff已经释放了,buff中存储的"结束时才打印\n"已经没了,变成了其他东西了 
加static让buff变量在整个程序的生命周期都有效,这样就没问题了
 - #include <stdio.h>
 
 - #include <string.h>
 
  
- int main(void)
 
 - {
 
 -     static char buff[1024] = "\0";
 
  
-     // 指定 buff 为缓冲区,_IOFBF 表示当缓冲区已满时才写入 stdout
 
 -     setvbuf(stdout, buff, _IOFBF, 1024);
 
  
-     fprintf(stdout, "结束时才打印\n");
 
 -   
 
 -     return 0;
 
 - }
 
  复制代码 
 
 
 |   
 
 
 
 |