在线等,cin检查用户输入,如果用户输入错误,怎么处理?在"add"处
函数实现max heap的加入、删除并以数组实现列出element.
在input==add处,如果用户输入错误,想返回heap>重新输入,怎么处理?
输出的样子大概是:
heap> add 5
heap> add 2
heap> add 3
heap> add 7
heap> list
7-5-3-2
heap>deletemax
7
heap>list
5-2-3
heap> quit
如果用户输入 add g(非数字变量)这个bug怎么修改好?谢谢
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <cmath>
#include <cstring>
#include "Maxheap.h"
using namespace std;
int main(){
Heap maxHeap;
int value;
string input;
bool running = true;
while(running){
cout << "heap> ";
cin >> input;
if(input=="quit"){
break;
}
else if(input=="add"){
cin >> value;
maxHeap.add(value);
}
else if(input=="list"){
maxHeap.list();
}
else if(input=="deletemax"){
maxHeap.deleteMax();
}
else{
cout<<"Error! "<<endl;
exit(1);
}
}
return 0;
}
[解决办法]
把这个再作修改放到add判断的后面
while(running){
INPUT:
.
.
.
for(int i = 4;input.length() - i > 0;i++)
if( input.c_str()[i] < '0' || input.c_str()[i] > '9')
goto INPUT;
[解决办法]
楼主,我建议你把 value这个变量,输入时,也用string类型输入,好检查一点输入的是数字还是字母,判断完后是数字用 atoi()函数转成数字,再进行其它操作。