2012-02-06 4 views
0

그래서 기본적으로 프로그램을 열고 파일을 열어야합니다. 프로그램이 사용자에게 파일 이름을 입력하도록 요청하고, 사용자가 처음으로 파일 이름을 정확하게 입력하면 작업이 작동합니다. 그러나 사용자가 이름을 잘못 입력하면 "잘못된 이름이 다시 시도됩니다."라고 표시되지만 사용자가 이름을 올바르게 입력하더라도 파일을 열 수 없습니다. 코드는 다음과 같습니다.C++ 오픈 파일 스트림

ifstream read_file(file.c_str()); 
while(true) 
{ 
    if(!(read_file.fail())) 
    { 
     ... 
    } 
    else 
    { 
     cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>"; 
    } 
    cin >> file; 
    ifstream read_file(file.c_str()); 
} 

무엇이 문제입니까, 어떤 생각입니까? 감사합니다

답변

5

루프 내부에서 read_file을 다시 선언하지만 루프 상단의 코드는 항상 루프 외부에서 read_file을 사용합니다.

이 대신 원하는 것입니다 :

ifstream read_file(file.c_str()); 
while(true) 
{ 
    if(!(read_file.fail())) 
    { 
     ... 
    } 
    else 
    { 
     cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>"; 
    } 
    cin >> file; 
    read_file.open(file.c_str()); /// <<< this has changed 
} 
+0

1. 또한 (read_file)이 if (! read_file.fail()) – stinky472

+0

과 동일하면이 점에 유의할 가치가 있습니다. – Richard

+0

고맙습니다. @stinky 고맙습니다. 그러나 코드를 그대로 두는 것이 더 보잘것입니다. – Gigi