我正在尝试制作一个程序,我使用链表来存储蛋糕的数据,目前我正在制作一个添加蛋糕的功能。这个函数将验证一些事情。我想验证,以便输入代码不能与链表中的现有代码相同。这是功能:
struct cookie
{
char code[10], name[100];
int stock, price;
struct cookie *next;
};
int validateCode(struct cookie *test, char kode[10]){
int check;
int flag;
while(test != NULL){
check = strcmp(test->code, kode);
if(check == 0){
flag = 0;
}
else{
flag = 1;
}
test = test->next;
}
if(flag == 1){
printf("%s already exists in the linked list", kode);
}
return flag;
}
我试图将 while 条件更改为:
对我都不起作用
好吧,原来我很愚蠢,哈哈,我找到了解决方案,感谢您的评论,非常有用的提示
int validateCode(struct cookie *test, char kode[10]){
int check;
int flag;
while(test != NULL){
check = strcmp(kode, test->code);
if(check == 0){
flag = 1;
break;
}
else{
flag = 0;
}
test = test->next;
}
if(flag == 1){
printf("%s already exists in the linked list", kode);
}
return flag;
}
如果你想检查列表中是否已经存在指定的数据,那么函数中的 while 循环应该在列表中找到数据后立即停止迭代。
还要注意,当两个字符串彼此相等时,标准 C 字符串函数
strcmp
返回 0
。因此,如果函数 strcmp
返回 0
那么这意味着数据存在于列表中。
可以通过以下方式声明和定义函数
int validateCode( const struct cookie *test, const char kode[] )
{
while ( test != NULL && strcmp( test->code, kode ) != 0 )
{
test = test->next;
}
return test != NULL;
}
如果数据存在于列表中,函数返回
1
。否则返回0
.
两个函数参数都应该用限定符
const
声明,因为指向的数据在函数内没有改变。并且该函数不应输出任何消息。函数的调用者将决定是否输出消息。