我的问题在于我不知道如何插入规则,其中如果用户在字符串上输入数字,则会cout发出警告说它无效,如果用户在等级上输入字符串/字符则相同.怎么样?我一直在尝试,但公式不起作用.
int x, cstotal = 100, extotal = 150;
double scorecs, exscore, labtotala, labtotalb, total;
string mystr = "";
cout << "Compute for: " << "\n" << "1. Laboratory Grade " << "\n" << "2. Lecture Grade" << "\n" << "3. Exit" << "\n";
cout << "Please enter a number: ";
cin >> x;
switch (x) {
case 1:
cout << "Compute for laboratory grade." << "\n";
cout << "Enter Student Name: ";
cin >> mystr;
cout << "Good day, " << mystr << " . Please provide the following grades: " << "\n";
cout << "CS Score: ";
cin >> scorecs;
cout << "Exam Score: ";
cin >> exscore;
labtotala = scorecs / cstotal * 0.6;
labtotalb = exscore / extotal * 0.4;
total = labtotala + labtotalb;
cout << "Your Laboratory Grade is " << total * 100 << "\n";
system("pause");
break;
case 2:
cout << "Compute for lecture grade." << "\n";
cout << "Enter Student Name: ";
cin >> mystr;
cout << "Good day, " << mystr << " . Please provide the following grades: " << "\n";
cout << "CS Score: ";
cin >> scorecs;
cout << "Exam Score: ";
cin >> exscore;
labtotala = scorecs / cstotal * 0.7;
labtotalb = exscore / extotal * 0.3;
total = labtotala + labtotalb;
cout << "Your Lecture Grade is " << total * 100 << "\n";
system("pause");
break;
Run Code Online (Sandbox Code Playgroud)
Aam*_*mir 10
cin设置一个failbit当它得到一个无效的类型的输入.
int x;
cin >> x;
if (!cin) {
// input was not an integer
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用cin.fail()检查输入是否有效:
if (cin.fail()) {
// input was not valid
}
Run Code Online (Sandbox Code Playgroud)