2014-12-06 5 views
-2

안녕하세요. 교수님이 ifstreams의 예를 보여주는이 웹 사이트에이 예를 게시했습니다. 어떻게 .txt 파일을 열 수 있습니까?파일이 ifstream에 열리지 않습니다

#include <iostream> 
#include <iomanip> // for setw 
#include <fstream> // for ifstream, ofstream 

using namespace std; 

int main() 
{ 
    char filename[25];  // a string for filename entry 

    int val;  // for reading integers from file 
    int sum = 0, count = 0;  
    double average; 

    ifstream in1;  // create an input file stream 

    do 
    { 
     in1.clear(); 
     cout << "Please enter the name of the input file.\n"; 
     cout << "Filename: "; 
     cin >> setw(25) >> filename; 

     in1.open(filename); 
     if (!in1) 
     cout << "That is not a valid file. Try again!\n"; 

    } while (!in1); 

    // PROCESS THE INPUT FILE 
    // Read all integer values and compute average 

    while (!in1.eof())  // while not end of file 
    { 
     in1 >> val;  // read an integer from file 

     if (!in1.fail())  // in case last call failed to read an int 
     {    // due to trailing white space at end of file 
    count++; 
     sum += val; 
     } 
    } 

    average = static_cast<double>(sum)/count; 

    cout << "There were " << count << " numbers in the file\n"; 
    cout << "Sum = " << sum << "\t\tAverage = " << average << "\n\n"; 

    in1.close(); 

    return 0; 
} 

이것은 매우 가중합니다! 그것은 내 컴퓨터 또는 뭔가 문제가 있습니까?

인용문

+0

스택 오버플로에 오신 것을 환영합니다! 이 코드를 실행할 때 정확히 무엇이 발생합니까? – Kelm

+0

절대 경로를 사용해 보셨습니까? – Borgleader

+0

코드를 실행하면 파일 이름을 입력하라는 메시지가 표시되지만 입력 한 파일을 찾을 수 없다는 메시지가 표시됩니다. – Demomomo

답변

2

날이 가정을 만들어 보자 : 당신은 어떤 IDE를 사용하고 당신이 상대 경로를 사용하고 있습니다.

IDE는 종종 프로젝트 주 디렉터리와 다른 디렉터리에서 이진 파일을 실행합니다. 절대 경로를 사용하거나 올바른 디렉토리를 찾거나 직접 파일을 실행하십시오.

+0

절대 경로를 사용해 보았지만 여전히 파일이 존재하지 않는다고 알려줍니다. 또한 Microsoft Visual Studio를 사용하고 있습니다. – Demomomo

+0

코드에서 파일 경로를 하드 코딩하고 작동하는지 알려주십시오. – Kelm

+0

여전히 작동하지 않습니다 : ( – Demomomo

0

처음부터해야 할 일은 오류를 이해하는 코드를 작성하는 것입니다.

.... 
    if (!in1) { // replace this bloc 
     cout << filename << " is not a valid file\n"; // print filename to find out any issues (truncated name, etc...) 
     cout << "Error code: " << strerror(errno)<<endl; // Get some system info as to why 
     char cwd[512];       // print current working directory. 
     getcwd(cwd, sizeof(cwd));    // in case your path is relative 
     cout << "Current directory is " << cwd << endl; 
     cout << "Try again !\n"; 
    } 

getcwd() 리눅스 아래로 작동하지만 윈도우에서, 대신 _getcwd()을 사용해야합니다 있습니다 : 그것은 또한 사용자가 나중에 그들이 문제가 발생할 때에, 디버깅, 이제 당신 만이 아니다 .

중요 비고 :

당신의 오류의 원인이되지 다음,하지만 나중에 문제가 발생할 수 있습니다 :

while (in1 >> val) {  // while read of file works 
     ... 

검색을 arround에 :

while (!in1.eof()) {  // while not end of file 
     in1 >> val;   // read an integer from file 
     ... 

은 다음과 선호 그래서 : 이유를 설명하는 많은 질문/답변이 있습니다.

관련 문제