Translate the statements inside the while loop into switch statements int main()
ID: 3828038 • Letter: T
Question
Translate the statements inside the while loop into switch statements
int main() {
int m;
cin >> m;
list<int>* HashTable = new list<int>[m];
char line[100];
while(std::cin.getline(line, 100)) {
string str(line);
if(str.size() == 0) {
continue;
}
if(str.substr(0,1) == "e") {
return 0;
}
if(str.substr(0,1) == "o") {
Output(HashTable, m);
continue;
}
int key;
stringstream convert_stm(str.substr(1,str.size()-1));
if(!(convert_stm >> key)) {
key = -1;
}
if(str.substr(0,1) == "i") {
Insert(HashTable, key, m);
}
if(str.substr(0,1) == "d") {
Delete(HashTable, key, m);
}
if(str.substr(0,1) == "s") {
Search(HashTable, key, m);
}
}
Explanation / Answer
int main() {
int m;
cin >> m;
list<int>* HashTable = new list<int>[m];
char line[100];
while(std::cin.getline(line, 100)) {
string str(line);
if(str.size() == 0) {
continue;
}
int key;
stringstream convert_stm(str.substr(1,str.size()-1));
if(!(convert_stm >> key)) {
key = -1;
}
// converting str.substr(0,1) to str.at(0)
// str.substr(0,1) returns first charcter in string format
// whle str.at(0) rreturns first character in char format
// switch case accepts char or integer only
switch(str.at(0)) {
case 'e':
return 0;
case 'o':
Output(HashTable, m);
break;
case 'i':
Insert(HashTable, key, m);
break;
case 'd':
Delete(HashTable, key, m);
break;
case 's':
Search(HashTable, key, m);
break;
}
}
}
Modified the code and put some comments.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.