我想比较两个char数组。但是,DoSomething()函数永远不会被调用。我无法弄清楚原因。
我做错了什么?
//The value the user types in will be stored here:
char TempStorage[]={0,0,0,0,0,0};
//User types in a sequence here:
GetInput();
//One of the sequences that TempStorage will be compared to.
char Sequence[]={1,2,3,4,0,0};
//If the user typed in "123400" then DoSomething().
if(memcmp(TempStorage, Sequence, sizeof(TempStorage) == 0))
{
DoSomething();
}
答案 0 :(得分:7)
错位的人。
if(memcmp(TempStorage, Sequence, sizeof(TempStorage) == 0))
应该是
if(memcmp(TempStorage, Sequence, sizeof(TempStorage)) == 0)
那些解析并放入数组的六个输入是真的吗?或者TempStorage
输入了一串ASCII字符?如果是后者,则应该使用字符串比较,并且应该为要比较的字符使用正确的ASCII代码。 (这是0x30
或'1'' for
1 .) A string comparison stops as soon as one of the strings is a NUL (
'\ 0'`),这意味着您不会比较无意义的填充(如果存在)。
char *input = GetInput();
if (strcmp(input, "1234") == 0) { ... }
答案 1 :(得分:3)
您的字符将解析为ASCII值,因此您应将其指定为:
char Sequence[]={'1','2','3','4',0,0};
或者比较实际的字符串,如:
char Sequence[]="1234";