![](/img/trans.png)
[英]How to get the strings from a file and store in a 2D char array and compare that 2D char array with a string in C?
[英]How to loop through an array of strings, compare each string to a char string in c
這是我循環遍歷字符串數組的嘗試。
我創建了一個 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:
./03.c: In function 'verifyVoterID':
./03.c:19:21: warning: comparison between pointer and integer
19 | if (uidDB[0][i] == voterID)
|
我也嘗試過使用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:
./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
我錯過了什么?
在我看來,有很多東西需要修改,我發布了下面的代碼和一些評論。 我希望這可以幫助你。 它在 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.