[英]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.我创建了一个 id 数组,将每个 id 与从控制台读取的 voterID 进行比较。
// 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: 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我也尝试过使用strcmp()
进行比较
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: 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.它在 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.