简体   繁体   中英

How to loop through an array of strings, compare each string to a char string in c

Here's my attempt to loop through an array of strings.

I created an array of ids, compared each id to a voterID which is being read from the console.

// helper function
int verifyVoterID(char *uidDB[], char *voterID)
{
  for (int i = 0; i < sizeof(uidDB[0]); i++)
  {
    if (uidDB[0][i] == voterID)
      return 0;
  }
  return 1;
}

int main()
{
  char *uidDB[] = {"001", "002", "003"}, *voterID;
  
  printf("\n\nEnter ID: ");
  scanf("%s", voterID);

  // Verify voter's ID
  if (voterID)
    verifyVoterID(uidDB, voterID) == 0 
    ? doSomthing() 
    : doSomethingElse();

  return 0;
}

OUTPUT:

./03.c: In function 'verifyVoterID':
./03.c:19:21: warning: comparison between pointer and integer
   19 |     if (uidDB[0][i] == voterID)
      |

I've also tried using strcmp() to compare

int verifyVoterID(char *uidDB[], char *voterID)
{
  for (int i = 0; i < sizeof(uidDB[0]); i++)
  {
    if (strcmp(uidDB[0][i], voterID) == 0)
      return 0;
  }
  return 1;
}

OUTPUT:

./03.c: In function 'verifyVoterID':
./03.c:19:24: warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast [-Wint-conversion]
   19 |     if (strcmp(uidDB[0][i], voterID) == 0)
      |                ~~~~~~~~^~~
      |                        |
      |                        char

What am I missing?

There're many things to modify in my point of view and I am posting the following code with some comments. I hope this helps you. It was tested on VS2019.

// return 0 if uidDB[i]==voterID, -1 if no match found
// I added const keyword since we're not going to change uidDB or voiterID in the function(read-only)
int verifyVoterID(const char* uidDB[], int uidLen, const char* voterID)
{
    for (int i = 0; i < uidLen; ++i)
    {
        if (!strcmp(uidDB[i], voterID)) // same as strcmp()==0.
            return 0;
    }
    return (-1);
}

int main(void)
{
    char voterID[8];    // NOT char* voterID;
    printf("\n\nEnter ID: ");
    scanf("%3s", voterID);  // read 3 characters only.

    const char* uidDB[] = { "001", "002", "003" };  // must be array of const char*
    const int uidDBLen = (sizeof(uidDB) / sizeof(uidDB[0])); // practical way to cal. size of array
    int verify_res = verifyVoterID(uidDB, uidDBLen, voterID);   // always pass the size of array together with the array

    if (verify_res == 0)
        doSomething();  // verify success
    else
        doSomethingElse(); // fail

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM