繁体   English   中英

C库函数用法有什么问题?

[英]What's wrong with this C library function usage?

我正在尝试比较两个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();
}

放置错误的括号。

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'`), .) A string comparison stops as soon as one of the strings is a NUL ( ,这意味着您不会比较无意义的填充(如果存在)。

char *input = GetInput();
if (strcmp(input, "1234") == 0) { ... }

您的字符将解析为ASCII值,因此您应将其指定为:

 char Sequence[]={'1','2','3','4',0,0};

或与实际字符串进行比较,例如:

char Sequence[]="1234";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM