c++ - while loop does not terminate with sentinel value
问题描述
I am a new coder for c++, i am learning it recently thus I may be missing basic elements and understanding. I am creating a c++ file which takes into account various information until -1 sentinel value is input and then it summarizes the information. My while loop does not terminate when I input -1 in student numbers. Can I get some advice and thoughts on the code? Am I missing something ? I am new so any criticism is welcome I just started a month ago. I am theorizing that my while loop may be too big should I put braces or take another approach to the problems, Thanks
while (studentnumber != -1)
{
cout<<"Enter student number:"<<endl;
cin>> studentnumber;
numberofstudents ++;
cout<<"Gender (1=male, 2=female):"<<endl;
cin>> gender;
if (gender==1){
gendermale ++;
}
else {
genderfemale++;
}
cout<<"Age:"<<endl;
cin>> Age;
average += Age/numberofstudents;
cout<<"Program of study:"<<endl;
cin>> prgstudy;
if (prgstudy=="COEN"){
prgstudycoen ++;
}
else
prgstudyelec++;
}
cout<<"Statistics:"<<endl;
cout<<"Total number of students is: "<<numberofstudents<<endl;
cout<<"Number of male students is: "<<gendermale<<endl;
cout<<"Number of female students is: "<<genderfemale<<endl;
cout<<"Average age of students is:"<<average<<endl;
cout<<"Number of COEN students:"<<prgstudycoen<<endl;
cout<<"Number of ELEC students:"<<prgstudyelec<<endl;
解决方案
您应该在阅读后立即添加对哨兵值的检查,而不是在它被处理后。
while ( true )
{
cout<<"Enter student number:"<<endl;
cin>> studentnumber;
if ( studentnumber == -1 )
{
break;
}
// Use studentnumber
}
while
您可以通过使用辅助函数读取输入来将检查置于 的条件中。
int readStudentNumber()
{
int studentnumber;
cout<<"Enter student number:"<<endl;
cin>> studentnumber;
return studentnumber;
}
while ( (studentnumber = readStudentNumber()) != -1 )
{
// Use studentnumber
}
推荐阅读
- reactjs - ReactJS 更改 PropTypes onHover ,这可能吗?
- typescript - 打字稿泛型,泛型中的新关键字扩展
- powershell - Windows Server 2012 R2:通过 PowerShell 从 Microsoft Update 在线检查更新
- javascript - 如何将 git-hooks 与电子应用程序连接起来
- python - Pandas 重新索引以填充日期索引
- python - 在 python 代码中获取属性错误
- c# - 检查文件是否存在于 FileInfo[]
- c++-winrt - Windows.UI.Xaml.Application 与 DependencyObject
- reactjs - nodejs如何在前端构建webserver以进行反应和角度的框架工作
- sql - PostGIS 查询从多边形表中选择所有多边形,该多边形表具有相交的几何图形,在传递的地理坐标列表中具有一个或多个点