2012-11-20 6 views
3

단어가 사전 텍스트 파일에 있는지 확인해야합니다. strcmp를 사용할 수는 있지만 문서에서 텍스트 줄을 가져 오는 방법을 실제로 모르겠습니다. . 여기에 내 현재 코드가 붙어있다.텍스트 파일에 단어가 있는지 확인하십시오. C++

#include "includes.h" 
#include <string> 
#include <fstream> 

using namespace std; 
bool CheckWord(char* str) 
{ 
    ifstream file("dictionary.txt"); 

    while (getline(file,s)) { 
     if (false /* missing code */) { 
      return true; 
     } 
    } 
    return false; 
} 

답변

2
char aWord[50]; 
while (file.good()) { 
    file>>aWord; 
    if (file.good() && strcmp(aWord, wordToFind) == 0) { 
     //found word 
    } 
} 

당신은 입력 연산자 단어를 읽을 필요가있다.

+1

시험 http://en.wikipedia.org/wiki/Lopado%C2%ADtemacho%C2%ADselacho%C2%ADgaleo%C2%ADkranio%C2%ADleipsano%C2%ADdrim ([Lopadotemachoselachogaleokranioleipsanodrimhypotrimmatosilphioparaomelitokatakechymenokichlepikossyphophattoperisteralektryonoptekephalliokigklopeleiolagoiosiraiobaphetraganopterygon]/w % C2 % ADhypo % C2 % ADtrimmato % C2 % ADsilphio % C2 % ADparao % C2 % ADmelito % C2 % ADkatakechy % C2 % ADmeno % C2 % ADkichl % C2 % ADepi % C2 % ADkossypho % C2 % ADphatto % C2 % ADperister % C2 % ADalktryon % C2 % ADopte % C2 % ADkephallio % C2 % ADkigklo % C2 % ADpeleio % C2 % ADlagoio % C2 % ADsiraio % C2 % ADbaphe % C2 % ADtragano % C2 % ADpterygon)! – HostileFork

2

std::string::find 작업을 수행합니다.

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

using namespace std; 


bool CheckWord(char* filename, char* search) 
{ 



    int offset; 
    string line; 
    ifstream Myfile; 
    Myfile.open (filename); 

    if(Myfile.is_open()) 
    { 
     while(!Myfile.eof()) 
     { 
      getline(Myfile,line); 
      if ((offset = line.find(search, 0)) != string::npos) 
      { 
      cout << "found '" << search << " \n\n"<< line <<endl; 
      return true; 
      } 
      else 
      { 

       cout << "Not found \n\n"; 

      } 
     } 
     Myfile.close(); 
    } 
    else 
    cout<<"Unable to open this file."<<endl; 

    return false; 
} 


int main() 
{ 

    CheckWord("dictionary.txt", "need"); 

    return 0; 
} 
+0

이것은 첫 번째 행에 발견 된 단어가 있는지 여부를 확인하는 것입니다. 검색하는 단어가 파일의 끝에있는 경우 어떻게됩니까? 위 코드를 어떻게 수정 하시겠습니까? – unixcreeper

+0

@unixcreeper 모든 행을 확인한 것처럼 보니 줄에 발견되면 "찾지 못했습니다"라는 메시지가 표시되고 EOF (파일 끝)까지 검색이 다시 실행됩니다. –

관련 문제