2015-10-07 28 views
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 ]); 
     } 
    } 
} 

回答

4

這是因爲輸入流中仍然有輸入。第一次撥打getchar()將看到這個輸入,抓住它然後返回。當您添加第二個getchar()時,不會再有輸入,因此它會阻止,直到您按下輸入。如果你想確保沒有任何輸入緩衝區留下比你可以使用:

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

這從流,直到它到達一個換行符消耗高達streamsize::max字符,然後只要消耗換行符,因爲它沒讀過streamsize::max個字符。這應該爲getchar()留下一個空的緩衝區。

相關問題