2017-03-26 1 views
-2

필자가 작성한 클래스 메서드는 단어를 다른 배열에 저장해야하지만 파일이 성공적으로 읽혔는지 여부에 대한 부울을 반환해야합니다. 논리 오류를 찾을 수 없습니다.bool 함수가 true 또는 false를 반환하지 못함

내가 공간도 여기에이

misspelledword  correctword correctword correctword 

처럼 될 수있는 탭

misspelledword  correctword 
misspelledword2  correctword2 
misspelledword3  correctword3 

하지만 형식으로 구분되어 이런 일에 읽고있다 파일의 형식은 내 코드

bool SpellChecker::loadFile(string filename) 
{ 

    ifstream ifile; 
    ifile.open(filename.c_str()); 
    if (ifile.fail()) 
    { 
     cout << "Error opening file" << endl; 
     return false; 
    } 
    string line; 
    int count = 0; 
    while (getline(ifile, line)) 
    { 
     istringstream iss(line); 
     getline (iss, misspelled[count], '\t'); 
     getline (iss, correct[count]); 
     count++; 
    } 
    if (ifile.good()) 
    { 
     return true; 
    } 
    ifile.close(); 
} 

false 또는 true를 반환하지 않아야하는 이유는 확실하지 않지만 임의의 수를 반환합니다. R 17, 그것이 어디서 왔는지 확실하지 않습니까?

+1

. 또한 'bool'은 '17'을 포함 할 수 없습니다. [mcve]를 게시하십시오. – Rakete1111

+0

컴파일러에서 경고를 표시해야합니다. 그렇지 않은 경우 경고 수준을 켜거나 켭니다. – chris

답변

0

루프가 실패하면 return 문이 누락되어 반환 값이 정의되지 않습니다. 컴파일러에서 경고해야합니다.

또한 good()은 EOF에 도달하면 거짓을 반환합니다. 따라서 good() 대신 eof() 및/또는 !fail()을 확인해야합니다.

더 이런 식으로 뭔가를 시도 :

bool SpellChecker::loadFile(string filename) 
{ 
    ifstream ifile(filename.c_str()); 
    if (!ifile) 
    { 
     cout << "Error opening file" << endl; 
     return false; 
    } 

    string line; 
    int count = 0; 

    while (getline(ifile, line)) 
    { 
     istringstream iss(line); 
     getline(iss, misspelled[count], '\t'); 
     getline(iss, correct[count]); 
     ++count; 
    } 

    return ifile.eof() && !ifile.fail(); 
    // or simply: 
    // return (bool) ifile; 
} 

또는 I/O 오류에 예외 처리를 가능하게 : 당신은 마지막에`return` 문을 놓치고

bool SpellChecker::loadFile(string filename) 
{ 
    ifstream ifile; 
    string line; 
    int count = 0; 

    ifile.exceptions(std::ifstream::badbit | std::ifstream::failbit); 
    try 
    { 
     ifile.open(filename.c_str()); 

     while (getline(ifile, line)) 
     { 
      istringstream iss(line); 
      getline(iss, misspelled[count], '\t'); 
      getline(iss, correct[count]); 
      ++count; 
     } 

     return true; 
    } 
    catch (const std::ios_base::failure &) 
    { 
     cout << "Error opening or loading file" << endl; 
     return false; 
    } 
} 
관련 문제