【问题标题】:While loop executing too early in C++循环在 C++ 中执行得太早
【发布时间】:2014-07-09 16:50:53
【问题描述】:

我根据第 5 章中的内容编写了一个简单的程序,列出了 C++ Primer 第 5 版中的 5.14,据说是为了获取用户的输入时间并使程序“等待”该时间(以秒为单位)。该程序使用 while 循环执行此操作,尽管等待时间是正确的,但语句执行的顺序不在我的系统上(带有 g++ 编译器的 Ubuntu 14.04)。我在一个 cout 语句中写了应该在 while 循环之前发生的语句。目前它只在 while 循环之后执行,尽管在我的代码中位于此循环之前。我不确定如何解决这个问题...

//Program to wait a certain number of seconds
//Also introduces the "while" loop

#include <iostream>
#include <ctime>

int main()
{
    using namespace std;
    float seconds;

    cout << "\nEnter the number of seconds you wish to wait for: ";

    cin >> seconds; 
    cout << "\n\nStarting countdown...\a";

    //clock_t is a variable type! It's in terms of system clock units though, NOT seconds

    clock_t delay = seconds * CLOCKS_PER_SEC;
    clock_t start = clock();

    while (clock() - start < delay);

    cout <<"\a and done!\n\n";

    return 0;
}

输入等待的秒数后,我得到的输出是系统在我输入的时间内闪烁光标,然后是“开始倒计时……完成!”一次全部。有什么想法吗?

【问题讨论】:

  • cout 被缓冲。使用cout.flush() 确保已打印整个缓冲区。

标签: c++ while-loop execution statements


【解决方案1】:

您想刷新cout 的缓冲区,例如:

cout << "\n\nStarting countdown...\a" << endl;

或者,如果您不想要回程车,请使用:

cout << "\n\nStarting countdown...\a" << flush;

或

cout.flush();

输出后;

【讨论】:

  • 完美!非常感谢。
【解决方案2】:

输出流将缓冲其输出,直到它被刷新。您可以手动刷新它,以确保您看到预期的输出:

cout << "\n\nStarting countdown...\a" << flush;

【讨论】:

    【解决方案3】:

    你也可以简单地输出到cerr而不是cout,那么就不需要显式刷新了,因为它会自动刷新。

    【讨论】:

    • 但是cerr和cout不一样。
    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2013-10-31
    • 2016-03-07
    • 2020-09-19
    相关资源
    最近更新 更多