在C++中,为了处理错误的输入(比如当程序要求输入一个整数但你输入一个字符时)它应该能够做某事然后循环重复输入.
当需要整数时输入字符时,我的循环无限迭代,反之亦然:
#include<iostream>
int main()
{
while (cout << "Enter a number" && !(cin >> num))
{
cin.sync();
cin.clear();
cout << "Invalid input; please re-enter.\n";
}
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能让程序再次提示输入新内容?
我为下面给出了二进制堆的程序 -
#include<iostream>
using namespace std;
/**
* Construct the binary heap.
* capacity is the capacity of the binary heap.
*/
class BinaryHeap
{
private:
int currentSize; // Number of elements in heap
int array[]; // The heap array
void buildHeap( );
void percolateDown( int hole );
public:
bool isEmpty( ) const;
bool isFull( ) const;
int findmini( ) const;
void insert( int x );
void deleteMin( );
void deleteMin( int minItem );
void makeEmpty( );
public :
BinaryHeap( …Run Code Online (Sandbox Code Playgroud)