[英]How to compare a array of strings with strcmp?
I have the code below, and I'm trying to compare the content of arrayx
with argv[2]
(user input argument upon execution), however even when the argv[2]
matches with the content of arrayx
, it bypasses to the else statement.我有下面的代码,我正在尝试将
arrayx
的内容与argv[2]
(执行时的用户输入参数)进行比较,但是即使argv[2]
与arrayx
的内容匹配,它也会绕过 else陈述。
If I try to use:如果我尝试使用:
strcpy(arg3, "inputstring" );
Then it works.然后它工作。
Also, if I try to printf(%s, arrayx)
, it prints out the correct string.此外,如果我尝试
printf(%s, arrayx)
,它会打印出正确的字符串。
Any idea why it does not work when I try to use the arrayx variable on strcmp?知道为什么当我尝试在 strcmp 上使用 arrayx 变量时它不起作用吗?
float float_arrayx[] = {
0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x0a
};
unsigned char arrayx[sizeof(float_arrayx) / sizeof(*float_arrayx)];
for (size_t j = 0; j < sizeof(arrayx) / sizeof(*arrayx); j++) {
arrayx[j] = (unsigned char)float_arrayx[j];
}
if (argc == 3 && (strcmp(argv[1], arg_help))) {
char arg3[100];
char arg2[32];
strcpy(arg3, arrayx );
strcpy(arg2, "-exec");
if(!strcmp(argv[1], arg2)) {
if(!strcmp(argv[2], arg3))
{
printf("\nDO SOMETHING....\n");
arrayx
has the length of the float array, so it has one character space for every item in the array. arrayx
具有浮点数组的长度,因此数组中的每一项都具有一个字符空间。 But C strings are null-terminated (the last char must be \0
), so if you want to use them with the standard string library functions, you need to get arrayx
null-terminated.但是 C 字符串是空终止的(最后一个字符必须是
\0
),所以如果你想将它们与标准字符串库函数一起使用,你需要让arrayx
空终止。 That means its size will need to be 1 greater.这意味着它的大小将需要大 1。 I'm not sure if you need to manually set the last space to zero, so I would just in case:
我不确定您是否需要手动将最后一个空格设置为零,所以我会以防万一:
unsigned char arrayx[sizeof(float_arrayx) / sizeof(*float_arrayx) + 1];
for (size_t j = 0; j < sizeof(float_arrayx) / sizeof(*float_arrayx); j++) {
arrayx[j] = (unsigned char)float_arrayx[j];
}
arrayx[sizeof(float_arrayx) / sizeof(*float_arrayx) + 1] = 0;
I'm also not familiar with arg_help
so I'm not sure if this will fix your problem, but it should be a start.我也不熟悉
arg_help
所以我不确定这是否能解决你的问题,但这应该是一个开始。
Taking no responsibility for the rest of the code, there's this...对代码的 rest 不承担任何责任,有这个...
To circumvent the "terminating null" problem, perhaps one could use为了规避“终止空”问题,也许可以使用
// You use sizeof for filling char array
size_t lenPswd = sizeof arrayx/sizeof arrayx[0];
// Use sizeof for comparing bytes, not two strings
if( strncmp( argv[2], arrayx, lenPswd ) == 0 )
Write code for clarity, not for density... The compiler will optimise as it does, but the reader shouldn't be expected to "notice" and parse the meaning of "."编写代码是为了清晰,而不是为了密度……编译器会照此进行优化,但不应期望读者“注意到”并解析“。”的含义。 applied to the return value.
应用于返回值。 Be clear...
清楚...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.