2012-03-19 45 views
0

如果用戶輸入他已輸入的USN號碼,則以下代碼工作正常。 ,但是如果他進入相同的USN排名第一的母馬時間被接受。我嘗試使用無限循環(;;)檢查 USN號碼,但我不知道如何退出無限循環。讀取唯一數據

有沒有解決方案。或者請告訴我如何終止無限循環。

void student :: GetData() 
{ 

    cout<<"Enter the number of students record wolud you like to enter(10 records as MAX): "; 

    cin>>MAX; 

    cout<<"\n Now enter the "<<MAX<<"students records\n"; 


    student so[10]; // SO is Student Object 

int i; 

    for(i=0;i<MAX;i++) 
     { 
    cout<<"Enter the Name: "; 
    cin>>so[i].name; 
    cout<<"\nEnter the USN num.: "; 
    cin>>so[i].USN; 


    for(int k=1;k<i;k++) 
    { 
    if (so[i].USN == so[k].USN); // here it finds the if the entered USN number exist or not 
     { 
      cout<<"The USN number exist try new one: "; 
      cin>>so[i].USN;  
     } // But after this statement if he enter the same exist USN number is accepting 

      //I need you guys to help me out at this point 
    } 

    cout<<"\n Enter the Three Marks: "; 

     for(int j=0;j<3;j++) 
    { 
     cin>>so[i].marks[j]; 
    } 
} 
} 

回答

0

這樣做:

if (so[i].USN == so[k].USN) { 
    ... 
} 
else break; 

而且你有一個語法問題有

if (so[i].USN == so[k].USN); <-- the ; is wrong here because it would end the if right away 
+0

這不起作用。如果第一個數字與當前數字不一致,它將退出循環。 – Mario 2012-03-19 18:33:01

0

要跳出循環使用.. '休息'。這將立即退出循環,並從循環底部繼續執行。或者,如果循環應退出並使其成爲條件的一部分,請使用變量進行存儲,例如:

bool shouldExit = false; 
while (shouldExit == false) 
{ 
    ... 
    if (someCondition) { 
     shouldExit = true; 
    } 
    ... 
}