此代码存在一些问题:
void selectOption(){
int choice; cin >> choice;
string name, surname;
switch(choice){
case 1:
showStudents();
break;
case 2:
cout <<"Name: "; cin >> name;
cout <<"Surname: "; cin >> surname;
addStudent(name,surname);
break;
case 3:
break;
default:
cout <<"DOES NOT SUPPORT" << endl;
break;
}
}
int main(){
while(true){
selectOption();
}
}
问题是,每当我输入字符串时,程序都会进入default
的情况,而不是让我输入选择。
第二个问题是,该程序只能在1、2和3上运行。如果我写5,则什么也不会发生(甚至不会进入default
情况)。
答案 0 :(得分:-1)
在尝试执行任何操作之前,您需要检查输入的值是否为整数,否则可能会收到一些非常令人讨厌的未定义行为。有many个简单的方法可以做到这一点,我个人的偏爱是使用std::all_of
中的algorithm
来检查输入中的每个字符是否都是数字。当然,这需要您像这样将输入作为std::string
#include <iostream>
#include <string>
#include <algorithm>
void showStudents() {
// Show students
}
void addStudent(std::string name, std::string surname) {
// Add student
}
void selectOption(){
int choice = 0;
std::string in = "";
std::cout << "Choice: " << std::flush;
std::cin >> in;
if (std::all_of(in.begin(), in.end(), ::isdigit)) {
choice = std::stoi(in);
}
std::string name, surname;
switch(choice){
case 1:
showStudents();
break;
case 2:
std::cout <<"Name: ";
std::cin >> name;
std::cout <<"Surname: ";
std::cin >> surname;
addStudent(name,surname);
break;
case 3:
break;
default:
std::cout << "DOES NOT SUPPORT" << std::endl;
return;
}
}
int main() {
while(true) {
selectOption();
}
}
这将产生您期望的行为-输入任何字符串,它将进入默认大小写,输入1
,2
或3
并执行该大小写。输出示例:
Choice: string
DOES NOT SUPPORT
Choice: 1
Choice: 2
Name: Name
Surname: Surname
Choice: 3
Choice: 4
DOES NOT SUPPORT
Choice: 5
DOES NOT SUPPORT
Choice: t
DOES NOT SUPPORT
Choice:
答案 1 :(得分:-1)
这似乎可以正常工作。有什么问题吗?
#include <iostream>
#include <string>
using namespace std;
void selectOption()
{
int choice;
string name, surname;
cin >> choice;
switch(choice)
{
case 1:
cout << "showStudents()" << endl;
break;
case 2:
cout <<"Name: "; cin >> name;
cout <<"Surname: "; cin >> surname;
cout << "addStudent(" << name << "," << surname << ")" << endl;
break;
case 3:
break;
default:
cout <<"DOES NOT SUPPORT" << endl;
break;
}
}
int main(){
while(true){
selectOption();
}
}
输出:
> 1 showStudents()
> 2
> Name: Rufus
> Surname: VonWoodson
> addStudent(Rufus,VonWoodson)
> 3
> 4
> DOES NOT SUPPORT
> 5
> DOES NOT SUPPORT
> 6
> DOES NOT SUPPORT
> ^C
> Command terminated
>
> Interrupt: Press ENTER or type command to continue
答案 2 :(得分:-2)
在开关中,您想测试整数的条件,如果您输入字符串作为变量选择,它将进入默认情况(希望我理解了这个问题)