C - 比较字符串字面量与字符数组 [英] C - Comparing string literal with character array
问题描述
我是C的新手,对于如何通过字符数组使用字符串仍然有点困惑。
I am new to C and am still a bit confused about how to use strings via character arrays.
在我的C程序中,我接受用户的命令:
In my C program, I am accepting commands from the user:
char command[20];
scanf("%s",command);
当然,我想知道他们输入了什么命令==hello),然后做某事)。我知道这是不可能在C,因为我比较字符串字面量到字符数组,但什么会是一个好的方法呢?我尝试使用strcmp(命令,hello),仍然有错误。
Of course, afterwards I want to figure out what command they typed (something similar to "if (command == "hello"), then do something"). I know this is not possible in C because I am comparing a string literal to a character array, but what would be a good way to it? I have tried using strcmp(command, "hello") and still got errors.
任何建议,你可以提供将非常感谢。谢谢!
Any advice you can provide would be very appreciated. Thank you!
推荐答案
当字符串相同时,strcmp返回0。我有代码使用strcmp比较字符数组到字符串字面量,我很困惑,当它不工作。结果是,我错了,假设它将返回1当字符串是相同的!
strcmp returns 0 when the strings are the same. I have code that uses strcmp comparing character arrays to string literals, and I was quite confused when it wasn't working. Turns out it was wrong for me to assume it would return 1 when the string are the same!
也许你犯了同样的错误吗?
Maybe you've made the same mistake?
这篇关于C - 比较字符串字面量与字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!