首页 > 解决方案 > 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;

标签: c++

解决方案


您应该在阅读后立即添加对哨兵值的检查,而不是在它被处理后。

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
}

推荐阅读