gpt4 book ai didi

c - 我认为的strtok问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:22 25 4
gpt4 key购买 nike

无法解决这个问题,有什么帮助吗?我不认为这是 strtok,我很确定这是我的代码。我想不通是什么想法。 Get 和 Set 导致 sigsevg。如果我在 num = strtof 等后面放一个 printf(),num 是正确的,但其他命令没有被正确解释。

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
float height;
float width;
float length;
}Box;

void usage(void)
{

printf("\nUsage: [command] [parameter] [amount]\n");
printf("commands:\n\tSet\n\tGet\n");
printf("parameters:\n\theight\n\twidth\n\tlength\n");
}


int main()
{
usage();
Box box1 = {0,0,0};
int loop = 1;
float num;
char cp[65], *delims = " !@#$%^&*():;/><.,\\?\"";
char *tok1, *tok2, *tok3, *temp;

beginning:
while(loop)
{

//Read the command from standard input
char str[65];
fgets(str, 64, stdin);
str[64] = 0;

//Tokenize the string
strncpy(cp, str, 64);
tok1 = strtok(cp, delims);
tok2 = strtok(NULL, delims);
tok3 = strtok(NULL, delims);

//Check if tok3 is float
num = strtof(tok3, &temp);
if(num != 0)
{

}
else
{
usage();
goto beginning;
}
if(tok1 == 'Get' && tok2 == 'height')
{
printf("%f", box1.height);
}
else if(tok1 == 'Get' && tok2 == 'width')
{
printf("%f", box1.width);
}
else if(tok1 == 'Get' && tok2 == 'length')
{
printf("%f", box1.length);
}
else if(tok1 == 'Get')
{
usage();
goto beginning;
}

if(tok1 == 'Set' && tok2 == 'height')
{
box1.height = num;
printf("%f", box1.height);
}
else if(tok1 == 'Set' && tok2 == 'width')
{
box1.width = num;
}
else if(tok1 == 'Set' && tok2 == 'length')
{
box1.length = num;
}
else if(tok1 == 'Set')
{
usage();
goto beginning;
}

}
return 0;
}

最佳答案

if(tok1 == 'Get' && tok2 == 'height')

C 字符串必须使用双引号,您不能使用== 来测试它们是否相等,您应该使用strcmp。 :

if(strcmp(tok1, "Get")==0 && strcmp(tok2, "height")==0)

关于strtof:

num = strtof(tok3, &temp);

如果您不必使用 temp,请使用空指针:

num = strtof(tok3, NULL);

以及使用 goto 的代码片段:

if(num != 0)
{

}
else
{
usage();
goto beginning;
}

goto 很难看,请改用 continue:

if(num == 0)
{
usage();
continue;
}

关于c - 我认为的strtok问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18049328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com