向大神求助cin的识别问题,新手第一次求教
#include <iostream>#include <string>
using namespace std;
int main ( )
{ //Welcome students to this program
cout << "Welcome to Student Information System, follow these steps and be satisfied with your result!" << endl<< endl<< endl;
//creat varibles as student number and percentage grade
int studentNumber = 0;
double percentageGrade = 0.0;
string letterGrade;
do
{
//Ask for student Number
cout <<"Enter your student number here: ";
cin >> studentNumber;
//Enter value -1 to termine the program
while(studentNumber == -1)
{ return 0;
}
//Check if the user dosen't type correctly
while(((studentNumber<100000000)||(studentNumber>999999999))&&(studentNumber != -1))
{ cin.clear();
cin.sync();
cout << "Please enter correctly,invalid numbers are not allowed."<< endl<< endl;
cout <<"Enter your student number here: ";
cin >> studentNumber;
while(studentNumber == -1)
{ return 0;
}
}
//Ask student user to enter his/her percentage grade
cout <<"Enter your percentage grade here: ";
cin >> percentageGrade;
//Check if the user dosen't type correctly
while((percentageGrade<0.0)||(percentageGrade>100.0))
{ cin.clear();
cin.sync();
cout << "Please enter correctly,invalid numbers are not allowed."<< endl<< endl;
cout <<"Enter your percentage grade here: ";
cin >> percentageGrade;
}
//Check out the letter grade
if ((percentageGrade>=0.0)&&(percentageGrade<=100.0))
{ if (percentageGrade>85.5)
{ letterGrade = "an A.";
}
else if(percentageGrade>73.5)
{ letterGrade = "a B.";
}
else if(percentageGrade>61.5)
{ letterGrade = "a C.";
}
else if(percentageGrade>49.5)
{ letterGrade = "a D.";
}
else
{ letterGrade = "a F.";
}
}
//Give the final comment
cout <<"Student number: "<<studentNumber<<", percentage grade: "<<percentageGrade<<"%."<<endl<<"This student will receive"<<letterGrade<<endl<< endl<< endl;
}
while(cin.fail());
}
以上是我的程序,作业是要求做一个学生成绩查询系统,根据学分百分比给出ABCDF的级别
要求是学生可以不停的查询(所以我用do while,应该while也可以),直到学生在要求输入学生号的时候输入-1来退出系统
我现在遇到的问题是,studentNumber和percentageGrade都是数字形式的变量,一旦cin的时候输入字母或符号就会无限死循环,所以我用cin.clear()和cin.sync()来解决这个死循环,
但问题就来了,我放了两个cin.clear()和cin.sync()分别给studentNumber和percentageGrade,但是只有studentNumber那部分会退出死循环,percentageGrade那部分如果输入字母或者符号,还是继续死循环,难道cin.clear()和cin.sync()只能用一次吗?