0
當我運行以下程序時,如果在退出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 ]);
}
}
}