문제

사용자에게 파일 이름을 제시하고 있습니다. 처음으로 유효한 파일 이름을 입력하면 작동합니다. 그러나 처음으로 유효하지 않으면 다른 모든 수표가 실패합니다. 이것을 어떻게 고칠 수 있습니까? 또한 디렉토리 만 지정한다고 가정 해 봅시다. 모든 텍스트 파일의 이름을 어떻게 얻고 얼마나 많은지?

int main() {

    ifstream inFile;
    int result;
    string filename;

    cout << "If the executable is not in the same directory as the\nfile, then a directory needs to be provided\n\n";
    while (true) {
        cout << "Enter the file name:  ";
        getline(cin, filename);
        inFile.open(filename.c_str(), ios::in);

        if (!inFile)
            cout << "\n**File failed to open**\n\n";
        else break;
    }

    result = countLOC(inFile);
    cout << "\nThere are " << result << " lines of code in \"" << filename << "\"\n\n";

    inFile.close();
    return 0;
}
도움이 되었습니까?

해결책

객체 'infile'의 오류 비트가 설정 되었기 때문입니다.
다른 일을하기 전에 오류 비트를 재설정해야합니다.

if (!inFile)
{
    cout << "\n**File failed to open**\n\n";
    inFile.clear();
}
else break;

다른 팁

부르다 분명한 호출을 열기 전에 주를 재설정합니다.

오류 플래그 등을 사용할 필요는 없습니다. 확인을 위해 infile.is_open () 함수를 호출 할 수 있습니다. infile.clear ()도 사용할 필요가 없습니다.

예 명확하게하십시오

사용자가 디렉토리를 제공하는 경우 FindFirst 및 FindNext를 수행해야합니다.

msdn.microsoft.com/en-us/library/zyzxfzac(vs.71).aspx

모든 파일을 그런 식으로 처리합니다.

그것을 지우십시오. 또한, 당신은 당신의 루프에서 휴식을 취할 필요가 없습니다. 나는 이것을 대신 제안합니다.

do {
    if (infile.fail())
       cout << "\n**File failed to open**\n\n";
    infile.clear()
    cout << "Enter the file name:  ";
    getline(cin, filename);
    inFile.open(filename.c_str(), ios::in);
} while(!infile)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top