【问题标题】:How to compare a string in a C program [duplicate]如何在C程序中比较字符串[重复]
【发布时间】:2017-03-27 00:40:51
【问题描述】:

我有一个关于如何在if 语句中比较字符串的问题。我正在从 Python 迁移到 C 并且在 Python 中比较字符串很容易,但是在 C 中我该怎么做呢?

我的程序是:

printf("Enter your choice 1.add\n 2.sub\n 3.mul\n 4.div\n");
string choice = get_string();

if (choice == "add")
{
    int c = calculate_add(a, b);
    printf("sum of %i and %i is %i\n", a, b, c);
}

当我运行这个时,我得到这个错误:

calculate.c:19:16: error: result of comparison against a string literal is
  unspecified (use strncmp instead) [-Werror,-Wstring-compare]
if (choice == "add")
           ^  ~~~~~

它说使用strncmp 来比较字符串,但是我该怎么做呢?

【问题讨论】:

  • 这一行是否正确 string selection = get_string();?
  • "但我不知道该怎么做" - 谷歌,研究和学习。网络上有很多例子。你检查了吗?
  • @lazy_coder 是的,因为我包含了 cs50 头文件:)
  • @CoolGuy 这是个好建议,但堆栈比谷歌好得多:)
  • @pkarthicbz 是的,但是对于这类初学者问题,请使用谷歌。你可以从那里得到很多例子。如果您阅读 downvote 按钮的工具提示,您会看到类似“发布没有显示任何研究工作”的内容。人们会投反对票。那是为了保持高质量的问题。如果您在 Google 上搜索过,您可能会更快地发现如何使用 strcmp。仅在您的研究失败后咨询 Stack Overflow。

标签: c if-statement


【解决方案1】:

简单地代替

if(choice == "add")

使用以下语法:

if(!strcmp(choice, "add"))

别忘了include <string.h>

【讨论】:

    【解决方案2】:

    使用来自<string.h>strcmp

    #include <string.h> // It might compile without it, but always add it for portability and so that your code compiles in all compilers that follow the C standard.
    
    int main() {
       int equals = strcmp("add", "add") == 0; // equals = true
    
       int greaterThan = strcmp("bad", "add") > 0; // greaterThan = 1
    
       int lessThan =  strcmp("123", "add) < 0; // lessThan < 0
    
    }
    

    所以在你的情况下:

    if (strcmp(choice, "add") == 0) { // This means choice = "add"
        int c = calculate_add(a, b);
        printf("sum of %i and %i is %i\n", a, b, c);
    }
    

    【讨论】:

    • 没有问题!很高兴帮助:)
    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多