0

I am newbie in C and I will be glad for any help with this program:

Task:

User will enter 4-7 letters (for example 'ADFG').

I have detached text file which contains about several thousand of words

(for example:

  • BDF
  • BGFK
  • JKLI
  • NGJKL
  • POIUE

etc.)

-its written in list without that marks

I want to make program, which find words from this text file, which are same as letters which user entered (In this case, when I entered ADFG it will find and display BDF, BGFK, NGJKL).

This is my code so far:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
    char enter[8],row[80];

    printf("4-7 different letteres: ");
    gets(enter);

    if (strlen(enter)>7 || strlen(enter)<4)
    {
        puts("incorrect number of letters"); 
        return 1;
    }

    typedef struct structure
    {
        char row[50];
    }Row;

    Row textrow[40000];

    FILE *file;
    file = fopen("words.txt","r");

    if (file==NULL)
    {
        printf("Error! File %s can not be opened.","words.txt");
        return 1;
    }

    int i=0;
    char words[30];

    while (!feof(file))
    {
        fscanf(file,"%s",&textrow[i].row[0]);
        for(int j=0;j<strlen(enter);j++)
        {
            for(int k=0;k<strlen(textrow[i].row);k++)
            {
                words=strchr(textrow[i].row[k],enter[j]);
                printf("%s",words);
            }
        }
        i++;
    }

    fclose(file);
    return 0;
} 

Thanks for any help.

jalopaba
  • 8,039
  • 2
  • 44
  • 57

2 Answers2

1

e.g. use strpbrk

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char *words[] = {
        "BDF", "BGFK", "JKLI", "NGJKL", "POIUE", NULL
    };
    char enter[8] = "ADFG";
    char **p;
    for(p = words; *p ; ++p){
        char *word = *p;
        if(strpbrk(word, enter)!=NULL){
            printf("%s\n", word);
        }
    }
/*
BDF
BGFK
NGJKL
*/
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

As others have commented, given your code is possibly able to compile and build as is, your problem is with the approach, you need to identify the steps necessary to accomplish what you desire. Create the algorithm. Here are some steps to do what I think you want to do:

Problem statement: Given a text file with many words, and user input of 1 or more characters, find all words in file that contain one or more of the characters user entered.

Steps: (approach)
1) Read all words of text file into a string array
2) Get user input string into char array
3) In Loop: Check each char of user input to each char of each string

len = strlen(userInputStr);

for(i=0;i<numWords;i++)  //numWords is number of words in file
{
    len2 = strlen(word[i]);//length of next word in file
    for(j=0;j<len;j++)
    {  
        for(k=0;k<len2;k++)
        {
             //check each char of user input against each char of current word
        }
    }
}
ryyker
  • 22,849
  • 3
  • 43
  • 87