2014-02-22 4 views
0

파일 I/O에 대한 질문이 있습니다.C++ do while 루프가 EOF를 계속 수행합니다.

#include <iostream> 
#include <fstream> 
#include <string> 

int main(int argc, char** argv) 
{ 
    using namespace std; 
    string InputFileName="", temp=""; //File Name entered on command line 

    int Factor1=0, Factor2=0, MaxNum=0; 
    if (argc < 2) 
    { 
     cout << "No File Name Specified\n"; 
     return 0; 
    } 
    else 
    { 
     //InputFileName = argv[1]; //Get File Name from command line arguments array 
     ifstream inf (argv[1]); //open file for reading 

     if(!inf) //check for errors opening file, print message and exit program with error 
     { 

      cerr << " Error opening input file\n"; 
      return 1; 
     } 


     do 
     { 
      inf >> Factor1; 
      inf >> Factor2; 
      inf >> MaxNum; 
      cout << "Factor 1: " << Factor1 << " Factor 2: " << Factor2 << " Maximum Number: " << MaxNum << "\n"; 
     }while(inf); 

    } 
    return 0; 
} 

입력 파일이 포함되어 있습니다 :

3 5 10 
2 7 15 

출력은 다음과 같습니다

Factor 1: 3 Factor 2: 5 Maximum Number: 10 
Factor 1: 2 Factor 2: 7 Maximum Number: 15 
Factor 1: 2 Factor 2: 7 Maximum Number: 15 

이 숙제를하지

이 내 코드입니다. 내가 C++ 수업을 듣고 나서 20 년이 지났습니다. 나는 C++에서 솔직히 노력하고있다. 나는 Visual Basic에서 일하는 대부분의 경력을 보냈다. 제 질문은 왜 while 루프가 EOF를 잡아 내지 않고 3 행을 출력하고 어떻게 해결할 수 있습니까? 아니면 잘못된 방향으로 가고 있습니까?

+2

들여 쓰기는 매우 잘못된 것입니다. –

+0

들여 쓰기는 stackoverflow 편집기로 복사 한 결과입니다. 사과드립니다. –

+0

@WilliamMichaelVondran : "제출"을 누르기 전에 수정할 수 있습니다. –

답변

3

은 I/O의 성공 여부를 예측할 수 없습니다. 당신 반환 값을 확인해야합니다

원래 코드가 무모 그런데 오 입력, 확인하지 않고 성공 입력 소비 에 계속 만 훨씬 나중에 물어, "다시 갔다 가정
while (inf >> Factor1 >> Factor2 >> MaxNum) // checks the value of "inf", i.e. 
{            // whether the input succeeded 
    cout << "Factor 1: " << Factor1 
     << " Factor 2: " << Factor2 
     << " Maximum Number: " << MaxNum << "\n"; 
} 

, 그게 실제로 합법적 이었습니까? "

관련 문제