2012-10-23 5 views
1

프로그램에서 cin 루프를 종료하는 데 문제가 있습니다. 내 프로그램이 파일 hw07data의 입력에서 읽어 리눅스 리디렉션을 사용, 데이터 파일은 다음과 같이 :Cin 루프가 종료되지 않음

100 20 50 100 40 -1 
A34F 90 15 50 99 32 -1 
N12O 80 15 34 90 22 -1 

첫 번째 부분은 클래스의 총 포인트이며, 다음 줄은 다음에 학생 ID 번호 그들의 점수는 모두 -1로 끝납니다.

내 문제 : 나는 hw07data < ./a.out, 누군가가 내 코드를 통해보고 나에게 몇 가지 힌트를 줄 수있는 명령을 실행할 때 내 while 루프는 종료하지? 나는 대답을 원하지 않는다. 숙제이기 때문에, 나는 단지 약간의 지침이 필요하다. 감사!!

#include <iostream> 
#include <iomanip> 
using namespace std; 

const int SENTINEL = -1;   //signal to end part of file 
const int LTAB = 8;    //left tab 
const int RTAB = 13;    //right tab 

int main() 
{ 
    cout << "Grant Mercer Assignment 7 Section 1002\n\n"; 
    cout << setprecision(2) << fixed << showpoint; 
    cout << left << setw(LTAB) << "ID CODE" << 
       right << setw(RTAB) << "POINTS" << 
       setw(RTAB) << "PCT" << setw(RTAB) << 
       "GRADE" << endl; 
    double Percentage,    //holds students percentage 
      AvgPercentage; 
    int Earnedpoints,    //earned points for specific student 
     Totalpoints,    //total points possible for all students 
     AvgPoints,     //average points for all students 
     NumClass;     //counts the number of students 
    Totalpoints = Earnedpoints = //set all vals equal to zero 
    AvgPoints = AvgPercentage = Percentage = NumClass = 0; 
            //first and last char for studentID 
    char Fchar,Lchar, Num1, Num2, Grade; 

    int TmpVal = 0;     //temporary value 
    cin >> TmpVal; 
    while(TmpVal != -1)    //reading in TOTAL POINTS 
    { 
     Totalpoints += TmpVal;  //add scores onto each other 
     cin >> TmpVal;    //read in next value 
    } 

    while(cin)      //WHILE LOOP ISSUE HERE! 
    { 
            //read in student initials 
      cin >> Fchar >> Num1 >> Num2 >> Lchar >> TmpVal; 
      while(TmpVal != -1) 
      { 
       Earnedpoints += TmpVal; //read in points earned 
       cin >> TmpVal; 
      } 
             //calculate percentage 
      Percentage = ((double)Earnedpoints/Totalpoints) * 100; 
      AvgPercentage += Percentage; 
      NumClass++; 
      if(Percentage >= 90)  //determine grade for student 
       Grade = 'A'; 
      else if(Percentage >= 80 && Percentage < 90) 
       Grade = 'B'; 
      else if(Percentage >= 70 && Percentage < 80) 
       Grade = 'C'; 
      else if(Percentage >= 60 && Percentage < 70) 
       Grade = 'D'; 
      else if(Percentage < 60) 
       Grade = 'F'; 
             //display information on student 


      cout << left << Fchar << Num1 << Num2 << setw(LTAB) << Lchar << right << setw(RTAB-3) << Earnedpoints << 
      setw(RTAB) << Percentage << setw(RTAB) << Grade << endl; 
      TmpVal = Earnedpoints = 0; 
    } 
    AvgPercentage /= NumClass; 
    cout << endl << left << setw(LTAB+20) << "Class size: " << right << setw(RTAB) << NumClass << endl; 
    cout << left << setw(LTAB+20) << "Total points possible: " << right << setw(RTAB) << Totalpoints << endl; 
    cout << left << setw(LTAB+20) << "Average point total: " << right << setw(RTAB) << AvgPoints << endl; 
    cout << left << setw(LTAB+20) << "Average percentage: " << right << setw(RTAB) << AvgPercentage << endl; 
} 

출력이 계속해서 새로운 입력을 요청합니다.

+0

표준 입력에서 EOF를 수신하면 종료하려고합니까? 여기를 참조하십시오 : http://stackoverflow.com/questions/3197025/end-of-fileeof-of-standard-input-stream-stdin –

+0

코드를 약간 정리하기 위해'struct'를 사용할 것을 권장합니다. – andre

+0

우리 수업의 과제에 대한 엄격한 지침을 따라야합니다. 또한 구조체 사용을 고려했지만 선생님은 어떤 고급 기술을 사용해도 실패하게됩니다. –

답변

1

당신은 당신이 getline를 사용하여 선으로 cin 라인을 읽고 그와 같은 결과 줄을 구문 분석 할 수 그래서 How to read until EOF from cin in C++

가 답을 찾을 수 있습니다 모든 실패에 대한 결과 및 스트림 상태!

1

당신해야 하면 입력이 성공적으로 항상 검사 : 당신이 밤에 오류가 입력의 끝에 도달 한 때문이라고 inducating eof()를 확인하려면 실패의 경우

if (std::cin >> TmpVal) { 
    // do simething with the read value 
} 
else { 
    // deal with failed input 
} 

.

오류를 처리하려면 std::istream::clear()std::istream::ignore()을 살펴보십시오.

#include <iostream> 
#include <sstream> 
#include <string> 

int main() { 
    int a, b; 

    std::string line; 
    while (std::getline(std::cin, line)) { 
     std::stringstream stream(line); 

     stream >> a >> b; 
     std::cout << "a: " << a << " - b: " << b << std::endl; 
    } 

    return 0; 
} 

편집 : 구문 분석을 확인하는 것을 잊지 마십시오

관련 문제