输出屏幕停留一秒钟

The output screen stays for a second?

本文关键字:一秒钟 停留 屏幕 输出      更新时间:2023-10-16

当我运行以下程序时,如果我在退出main之前只有一次对getchar()的调用,控制台窗口只会保持打开一秒钟。如果我向getchar()添加第二个调用,那么它将保持控制台窗口打开。这是什么原因呢?

#include <iostream>
using namespace std;
void selectionSort(int [], const int, bool (*)( int, int ));
bool ascending ( int, int );
bool descending ( int, int );
void swap(int * const, int * const);
int main()
{
    const int arraySize = 10;
    int a[ arraySize ] = { 1, 22, 2 ,44 ,3 , 4, 6, 0, 7, 5 };
    int order;
    cout << "Enter 1 to sort in ascending order and 2 for descending " << endl;
    cin >> order;
    if ( order == 1 )
        selectionSort( a, arraySize, ascending );
    if ( order ==2 )
        selectionSort( a, arraySize, descending );
    for ( int i = 0; i < arraySize; i++ )
        cout << a[i] << " ";        
    cout << endl;
    getchar();
              //getchar(); only if i use this version of getchar output screen remains
    return 0;
}
bool ascending ( int x, int y )
{
    return x < y;
}
bool descending ( int x, int y )
{
    return x > y;
}
void swap(int * const x, int * const y)
{
int temp = *x;
*x = *y;
 *y = temp;
}
void selectionSort(int work[], const int size, bool (*compare)( int, int ))
{
    for ( int i = 0; i < size - 1; i++ )
    {
    int smallestOrLargest = i;
        for ( int index = i + 1; index < size; index++ )
        {
            if ( !(*compare)( work[ smallestOrLargest ], work[ index ] ) )
                swap( &work[ smallestOrLargest ], &work[ index ] );
        }
    }
}

这是因为在输入流中仍然有输入。第一次调用getchar()将看到这个输入,抓住它,然后返回。当您添加第二个getchar()时,没有更多的输入,所以它会阻塞,直到您按下enter。如果您想确保输入缓冲区中没有剩余内容,则可以使用:

std::cin.ignore(std::numeric_limits<streamsize>::max(), 'n');

从流中读取最多streamsize::max个字符,直到到达换行符,然后只要没有读取streamsize::max个字符,就会读取换行符。这应该为getchar()留下一个空缓冲区。