如何在文本文件中搜索字符串中的单词?

时间:2016-02-23 03:54:56

标签: c++

尝试将来自用户输入的单词与来自文本文件的字符串进行匹配。 基本上,文本文件是包含许多单词的单个字符串,它充当"字典"。 运行此代码时,它会在打开文件后崩溃。 (以****标记) 如何更改它以正确匹配来自用户输入的字符串与文本文件中的字符串。

任何帮助将不胜感激,谢谢。

const int Size = 81;                // 80 characters for the line + 1               for the '\0'
const int MaxNumberOfWords = 10;

int main() {
  char input[81], temp[81], fin[81];
  printf("Input a string\n");
  fgets(input, 81, stdin);
  int len = strlen(input);


  char *div;
  div = strtok(input, " ");
  while (div != NULL) {
    printf("%s\n",div);
    div = strtok(NULL, " ");


    ifstream inStream;                          // declare an input stream for my use
    char theWords[ MaxNumberOfWords][ Size];    // Array to store words from input line
    int wordRow = 0;                            // Row for the current word
    char wordToLookup[ Size];                   // word to lookup
    bool wordWasFound = false;                  // flag to track whether or not word is found
    char c;                                     // stores return character after input

    inStream.open( "C:\\Users\\dqiao4\\Desktop\\Dev-Cpp\\dictionaryMax6.txt");
    assert( ! inStream.fail() );  // make sure file open was OK


    //*****this is where the code crashes
    while ( inStream >> theWords[ wordRow]) {
      wordRow++;
    }



    for (int i=0; i<wordRow; i++)  {
      // See if this word matches
      if ( strcmp( div, theWords[ i]) == 0 ){
        wordWasFound = true;
        break;      // quit looking
      }
    }
  }
}

2 个答案:

答案 0 :(得分:0)

int main(){

char input[81];int i=0,j=0,k=0;
cout<<"Input a string ";
while(i<=80){
 input[i]=getch();
 cout<<input[i];
 if(input[i]=='.')
 break;      
 i++;
}
ifstream File("C:\\User\\New.txt");
string line;
if(File)
{   
    while(getline(File, line))
    {
        char buff[1024];
        strcpy(buff, line.c_str());
        while(j<35){
            k=0;
          while(k<i){
            if(buff[j]==input[k])
            {
                int j1=j,k1=k;
                while(true){
                  if(buff[j1]==input[k1])
                    {
                        if(input[j1]=='.'){
                            cout<<"match";
                            return 0;
                        }   
                        j1++;k1++;
                    }
                    else
                    break;
                }
          }k++; 
         }j++; 
        cout<<endl;  
    }
}

} }

答案 1 :(得分:0)

#inlude <sstream>
#include <string>

在您的源代码中,并在字符串流缓冲区中读取文本文件,将其转换为字符串并执行

auto pos = file_in_str.find("word_to_find");

该pos是文件中单词的起始索引