微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

比较 C 中结构指针中的字符串

如何解决比较 C 中结构指针中的字符串

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct person {
   char user[50];
   char password[50];
   int amount;
};
int i=0;
int h=0;
int *n=&h;
struct person *p = NULL;
void adduser();
int main()
{
    int x;
     printf("Welcome to the bank\n");
    printf("what would you like to do\n");
    printf("type 1 to add a user\n");
    printf("type 2 to add to balance\n");
    printf("type 3 to take from balance\n");
    printf("type 4 to check from balance\n");
    scanf("%d%*c",&x);
    if(x==1){
        adduser();
    }
    else if (x == 2){
        printf("2");
    }
    else if (x == 3){
        printf("3");
    }
    else if (x == 4){
        printf("4");
    }
    else{
        main();
    }
}
    
void adduser(){
    struct person *temp = realloc(p,*n * sizeof(struct person));
    if (temp != NULL)
    p = temp;
    printf("n=%d\n",*n-1);
    printf("enter your new username\n");
    scanf("%s",&(p+*n)->user);
    int o=*n-1;
    for (i;i<=o;i++)
    {
        if(strcmp((p+*n)->user,(p+i)->user) == 0)
        {
            printf("user already exists");
            adduser();
        }
    }
    printf("enter your new password\n");
    scanf("%s",(p+*n)->password);
    *n+=1;
    main();
}

你好,我是 C 的初学者,我正在尝试使用此代码查看与我的结构中类似的用户输入字符串。

   for (i;i<=o;i++)
    {
        if(strcmp((p+*n)->user,(p+i)->user) == 0)
        {
            printf("user already exists");
            adduser();
        }
    }

我的代码应该要求用户输入他们的新用户(至少是我发布的)并检查是否存在类似的用户,但我的循环被忽略了,我不知道如何处理它。我觉得我的问题出在别处,但我无法弄清楚。此外,我可能犯了一些基本错误,因为我对结构和指针很陌生。

我尝试在线搜索解决方案,但找不到类似的情况。

解决方法

这段代码显然是错误的:

struct person *temp = realloc(p,*n * sizeof(struct person));

因为我们几乎立即要做:

scanf("%s",&(p+*n)->user);

这确实需要阅读

struct person *temp = realloc(p,(*n + 1) * sizeof(struct person));

此外,

for (i;i<=o;i++)

显然是错误的,应该是

for (i=0;i<=o;i++)

正如 dxiv 指出的那样,i 确实应该在此 for 循环中声明,而不是作为全局声明。

顺便说一下,您是否遇到循环问题?我很少看到 main() 的递归调用。这真的很聪明,但是只有在编译时进行了优化(反过来更难调试),这段代码才能很好地工作。建议更换

else{
    main();
}

和其他调用 main() 并在所有 main() 周围无限循环(最终将在输入阶梯上具有循环退出条件或条件 break; 语句。>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。