Сравнение пользовательской строки ввода с элементами массива строковых литералов - PullRequest
0 голосов
/ 10 апреля 2020

У меня проблемы со сравнением строки ввода пользователя с подстрокой, хранящейся в массиве указателей.

Что-то не так с тем, как я написал функцию fgets?

Вот функция, которую я реализую:

void printForIngredient(void){

  char ingredient[50]; 
  printf("Give the name of the ingredient:");
  fgets(ingredient, 50, stdin); 
  //scanf("%s", ingredient);
  int j=1; 

  //traverse through array, look for recipes which are indicated with 0 in front
  //if recipe is found, look at ingredients inside recipe, which are indicated with 1 in front
  //if ingredient matches, print recipe found 
  for(int i=0; i<14; i++){
    if(rawRecipes[i][0]=='0'){
      if(strcmp(&rawRecipes[i+j][1], ingredient) == 0){
        printf("%s\n", &rawRecipes[i][1]); 
        j++;
      }
    }
  }


}

, а вот массив, с которым сравнивается ввод:

char *rawRecipes[]={"0Broccoli Coleslaw","1olive oil","1white vinegar","1broccoli","0Creamy Broccoli Salad","1broccoli","1white sugar","1red onion","1white wine vinegar","0Minnesota Broccoli Salad","1eggs","1broccoli","1red onion",""};

Например, для ввода

broccoli

Я ожидаю следующий вывод

Broccoli Coleslaw
Creamy Broccoli Salad
Minnesota Broccoli Salad

edit Я только что понял, что алгоритм не работать, даже после того, как я изменил код, чтобы превратить \ n в '\ 0' в конце ингредиента, введенного пользователем. Может кто-нибудь подсказать, где может быть ошибка logi c?

1 Ответ

0 голосов
/ 10 апреля 2020

fgets также хранит '\n' символов, чтобы strcmp возвращал правильный результат, вы должны удалить этот символ новой строки из введенных строк, удобная функция для этого - strcspn.

Чтобы найти ингредиент в рецепте, вы можете использовать strtok, чтобы сравнить каждое слово рецепта с введенным ингредиентом.

Бегущий образец

#include <stdio.h>
#include <string.h>
#include <ctype.h> //toupper

void printForIngredient(void);

int main()
{
    printForIngredient();
}

void printForIngredient(void)
{
    char *rawRecipes[] = {"0Broccoli Coleslaw", "1olive oil", "1white vinegar", "1broccoli", "0Creamy Broccoli Salad", "1broccoli", "1white sugar", "1red onion", "1white wine vinegar", "0Minnesota Broccoli Salad", "1eggs", "1broccoli", "1red onion", ""};

    char ingredient[50], *ptr1, temp[50];

    printf("Give the name of the ingredient: ");
    fgets(ingredient, 50, stdin);
    ingredient[strcspn(ingredient, "\n")] = '\0'; //finds '\n' and replaces it with null-terminator
    ingredient[0] = toupper(ingredient[0]);  //capitalize ingredient first letter

    for (int i = 0; i < 14; i++)
    {
        if (rawRecipes[i][0] == '0') //only strings beggining in 0 will be compared, make sure this is what you want
        {
            ptr1 = &rawRecipes[i][1];
            strcpy(temp, ptr1);      //copy, can't tokenize string literals
            char *token;
            token = strtok(temp, " "); //tokenize recipe

            while( token != NULL ) 
            {
                if(strcmp(token, ingredient) == 0)
                {
                    printf( " %s\n", ptr1 );
                    break;
                }
                token = strtok(NULL, " ");
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...