C ++无限循环,返回问题
C++ Infinite-loop, Issue with returning
void phonebookmenu() {
phonebook ph;
string str;
cin.ignore();
cout << "PH> ";
getline(cin, str); //Input from user.
string buf; // Have a buffer string.
stringstream ss(str); // Insert the string into a stream.
vector<string> tokens; // Create vector to hold the words.
while (ss >> buf){
tokens.push_back(buf); //Adds all the words inside the vector.
}
while (true){
if (tokens[0] == "add"){
ph.add(tokens[1],tokens[2]);
}
else if(tokens[0] == "lookup"){
ph.lookup(tokens[1]);
}
else if(tokens[0] == "change"){
ph.change(tokens[1],tokens[2]);
}
else if(tokens[0] == "alias"){
ph.alias(tokens[1],tokens[2]);
}
else if(tokens[0] == "quit"){
//Return to the "Main-menu"
}
else{
cout << "Invalid input" << endl;
}
}
所以我从 "Main-menu" 调用此菜单,但在我输入类似 "Add peter 123" 的内容后,它会执行 returns 到 "Main-menu" 的功能,我不想。它应该回到
cout << "PH> ";
所以我可以继续做手术
循环不围绕 cout/input/determine/do something
逻辑。仅在 determine/do something
左右。将 while
移到 cout
之前,看看会发生什么。
请务必将最有帮助的答案标记为答案。
void phonebookmenu() {
phonebook ph;
string str;
cin.ignore();
cout << "PH> ";
getline(cin, str); //Input from user.
string buf; // Have a buffer string.
stringstream ss(str); // Insert the string into a stream.
vector<string> tokens; // Create vector to hold the words.
while (ss >> buf){
tokens.push_back(buf); //Adds all the words inside the vector.
}
while (true){
if (tokens[0] == "add"){
ph.add(tokens[1],tokens[2]);
}
else if(tokens[0] == "lookup"){
ph.lookup(tokens[1]);
}
else if(tokens[0] == "change"){
ph.change(tokens[1],tokens[2]);
}
else if(tokens[0] == "alias"){
ph.alias(tokens[1],tokens[2]);
}
else if(tokens[0] == "quit"){
//Return to the "Main-menu"
}
else{
cout << "Invalid input" << endl;
}
}
所以我从 "Main-menu" 调用此菜单,但在我输入类似 "Add peter 123" 的内容后,它会执行 returns 到 "Main-menu" 的功能,我不想。它应该回到
cout << "PH> ";
所以我可以继续做手术
循环不围绕 cout/input/determine/do something
逻辑。仅在 determine/do something
左右。将 while
移到 cout
之前,看看会发生什么。
请务必将最有帮助的答案标记为答案。