【问题标题】:How do I make the console print things one at a time in C++ the way Java and Python do?如何让控制台像 Java 和 Python 那样在 C++ 中一次打印一个东西?
【发布时间】:2021-09-04 02:04:38
【问题描述】:

我试图通过创建一个程序来有效地找到highly composite numbers 来感受C++,但我面临着不便。控制台等待,然后立即打印所有内容。我希望它像 Java 和 Python 那样一次打印一个东西。我该怎么做?

代码如下:

#include <iostream>
int main(){
    int record=0; //Highest number of factors found in a number so far
    for(int n=1; n<2147483647; n++){
        int factors=1;
        for(int PPF=2; PPF<=n; PPF++){ //PPF="Possible Prime Factor"
            bool isPrime=true;        
            for(int i=2; i<PPF; i++){ //
                if(PPF%i==0){         //Determining if the PPF is prime
                    isPrime=false;    //
                    break;
                }
            }
            if(isPrime){
                if(n%PPF==0){ //Here is where I calculate the number of factors n has based on its prime factorization.
                    int PRP=1; //PRP="Prime Raised to Power"
                    int pow;
                    for(pow=1; n%(PRP*PPF)==0; pow++){ //Finding the exponent of a specific prime factor
                        PRP*=PPF;
                    }
                    factors*=pow;
                }else{
                    break;
                }
            }
        }
        if(factors>record){
            record=factors;
            std::cout<<n; //Print the highly composite number
            printf("\n"); //Gotta make a new line the old-fashioned way cuz this is a low-level language
        }
    }
}

我正在使用 CodeRunner 和所有必要的 C/C++ 扩展在 VS Code 上运行它。

【问题讨论】:

  • std::cout&lt;&lt;n; //Print the highly composite number printf("\n"); 替换为 std::cout &lt;&lt; n &lt;&lt; std::endl; 看看是否会有所不同。
  • 做到了。谢谢!

标签: c++ printing console


【解决方案1】:

更准确地说,您需要std::flushstd::endl 打印一个换行符并刷新,但刷新没有中断。您也可以打印到std::cerr,它没有缓冲,直接打印所有内容。

【讨论】:

  • 好吧,我确实想要换行符。 std::cerr 没有缓冲是什么意思?
  • 缓冲输入正是您所经历的。为了节省时间,数据被收集、缓冲,然后在缓冲区已满或请求刷新时以大块的形式转储到底层媒体。缓冲通常比一个接一个的写入快几个数量级,而且它是常规流的默认设置,因为如果您不想要峰值性能,为什么要使用 C++?
  • @zucculent 这是导致延迟的缓冲。 C++为了提高效率使用缓冲区进行输出,通常只有在缓冲区满时才写入输出。
  • @infinitezero 此答案包含该问题的解决方案,但以 "更准确地说..." 开头的答案不是一个好主意。目前尚不清楚您指的是哪些内容。在给定的上下文中,我假设它是一个评论。然而,cmets 有自己的生命周期,随时可能消失。最好在问题开始时发布您所指的陈述,例如“将 X 行替换为 Y 行,更准确地说,您需要刷新....”
猜你喜欢
  • 2022-10-07
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多