簡體   English   中英

printf 不在 Eclipse 的控制台上打印?

[英]printf not print on the console in eclipse?

#include<stdio.h>

int main() {
    int n, s, i;
    do {
        printf("n= "); // here is the problem ?
        scanf("%d", &n);
    } while (n<100 || n <= 0);
    s = 0;
    i = 0;
    while (i <= n) {
        i = i + 2;
        s = s + i;
    }
    printf("s=%d", s);
    getchar();
    return 0;
}

我在 eclipse c/c++ 中運行它,它沒有先打印“n=”。 但是當我在另一個 IDE(如 DEV-C++ 或 VS 2017)中運行它時,它運行良好。 在 printf 之后添加這一行時,我按預期運行。

fflush(stdout);

這里有什么問題 ?

除非刷新緩沖區,否則printf不會打印到屏幕

看起來您的流已緩沖。 一旦您刷新緩沖區,您寫入stdout和其他流的數據將被緩沖並且所有輸出。 這允許更好的性能,因為 IO 在所有 CPU 操作中是最慢的。

此時,您至少有以下選擇:

  1. 每次使用printf時通過調用fflush( stdout )顯式刷新緩沖區
  2. 禁用緩沖setbuf(stdout, NULL);
  3. 通過在printf字符串末尾使用換行符\\n來刷新緩沖區 例如: printf("n= \\n");

您的代碼在某些環境中工作可能是因為在那里禁用了緩沖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM