【问题标题】:in c language ask the user for his name , if the name is in the DB ,print “welcome (name)”, if not print “name isn't in DB在c语言中询问用户他的名字,如果名字在数据库中,打印“欢迎(名字)”,如果不是打印“名字不在数据库中
【发布时间】:2021-11-30 12:12:29
【问题描述】:

我用 c 语言编写了下面的代码,但问题是 (if) 总是给我错误

char DB[][50]={"ahmed alla","Shady Ibrahim","Sara Sedky","Mohamed Ezz"};
    char name[50];
    fgets(name,50,stdin);
    int flag=1;
    for(int i=0;i<4;i++)
    {
        if(name==DB[i])
        {
            flag=0;
            printf("welcome %s \n",name);
        }
    }
    if(flag)
    {
        printf("sorry your name is not in the DB!");
    }

它总是打印“抱歉你的名字不在数据库中!”不管叫什么

【问题讨论】:

  • 我认为你应该使用 strcmp 而不是 ==。并且 fgets 总是在输入的字符串之后添加一个新行。
  • if(name==DB[i]) --> if (strcmp(name, DB[i]) == 0)

标签: arrays c string if-statement


【解决方案1】:

两点:

首先, fgets() 将换行符视为有效字符,并将其包含在复制到传递的缓冲区的字符串中。确保从 name 缓冲区中删除尾随换行符。在fgets()之后,可以吗

name[strcspn(name, "\n")] = 0;

Documentation on strcspn.

其次,在C中,使用strcmp()比较两个字符串

if (strcmp (name, DB[I]) == 0) {
  // strings are same

Documentation on strcmp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2010-10-19
    • 2023-03-18
    相关资源
    最近更新 更多