【发布时间】: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