输出屏幕停留一秒钟
The output screen stays for a second?
当我运行以下程序时,如果我在退出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()
留下一个空缓冲区。
相关文章:
- 使用strcpy将char数组的元素复制到另一个数组
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在 c++ 中拥有一组结构的正确方法是什么?
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- nlohmann-json将一个数组插入到另一个数组中
- redis_client::get 需要一秒钟以上的时间来回复
- 执行/在循环中停留一段时间,例如 1 分钟
- 在不到一分钟的情况下,在一秒钟内显示计时器
- 使用结构显示军事时间,并将一秒钟的时间添加到用户输入(C )中
- 每隔几秒钟移动一次对象
- 一秒钟后,OpenCV窗口消失了
- 随着时间的推移,每几秒钟喷一次精灵SFML C++
- WinSock closesocket() 调用在某些计算机上需要一秒钟
- Win32控制台在一秒钟后消失
- 输出屏幕停留一秒钟
- 一秒钟计时器
- 一秒钟有多少个滴答声
- Win32:测试鼠标是否停留了一秒钟