C Language Two-Dimensional Array String Question

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

It hasn't been long since I learned C language.

I'm asking you a question because I'm trying to implement Python's dictionary in C language, but I can't do this or that because of an error.

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

int main(void) {
  char dic[20][2];
  int num,i,n,m;
  printf ("How many elements should we create?" >> ");
  scanf("%d",&num);

  for (i=0;i<num;i++){
    printf("key, value >>",i+1) of the %dth element;
    scanf("%c %c",&dic[i][0],&dic[i][1]);
  }

  printf("{");
  for (n=0;n<num;n++){
    printf("%c:%c",dic[n][0],dic[n][1]);
    printf(",");
    }
  printf("}");

  printf("Enter the key value of the value you want to find" >> ");
  char key;
  scanf("%c",&key);
  for (i=1;i<num+1;i++){
    if (strcmp(key,dic[i][0]) == 0){
      printf("%c",dic[i][1]);
    }
  }
  return 0;
}

c

2022-09-20 08:48

1 Answers

#include <stdio.h>

int main(void) {
    char dic[20][2];
    int num, i, n, m;
    printf ("How many elements should we create?" >> ");
    scanf("%d", &num);

    getchar();

    for (i = 0; i < num; i++) {
        printf("key, value >>", i + 1) of the %dth element;
        scanf("%c %c", &dic[i][0], &dic[i][1]);
        getchar();
    }

    printf("{");
    for (n = 0; n < num; n++) {
        printf("%c:%c ", dic[n][0], dic[n][1]);
    }
    printf("}");

    printf("Enter the key value of the value you want to find" >> ");
    char key;
    scanf("%c", &key);
    For (i = 1; i < num; i++) { // I don't know why you did num+1..?
        if (key == dic[i][0]) {
            printf("%c", dic[i][1]);
        }
    }
    return 0;
}

I fixed it like this. I'm still a freshman, so I can't give you a detailed answer First of all, we need the concept of buffers. (I think you need to google it separately here. The getchar() function is used for that reason.) Also, strcmp is used to compare strings, not letters strcmp(key,dic[i][0]) == 0 should not be used. I understand that the strcmp function compares the two characters until the null character comes out. However, since characters don't have letters attached to them, if you compare them, you'll move on until you find letters that are somewhere in your memory. Then of course, key and dic[i][0] will be recognized as different values, right? I don't know if my answer will help. And I'm also a learner, so there may be errors, so I think you should google the details...!


2022-09-20 08:48

If you have any answers or tips


© 2022 pinfo. All rights reserved.