在c中使用strtok()和strtod()从命令行分隔9个double类型的数字



我有以下命令行界面,其中-k参数看起来像这样:-k "0.0:-1.0:0.0:-1.0:4.0:-1.0: -1.0:0.0">。这是9个用":">分隔的双精度值。我已经设法将第一个双精度值0.0与strtok()和strtod()分开,但我需要所有9个值,我似乎没有找到一种有效的方法来做到这一点。

也许有一个循环,然后将值保存在2x3数组中,但还没有结果。最后,我必须使用这些数字来操作图像中的像素。注意,这些都是示例数字,用户可以键入从0到255的任何双精度值。希望有人能提供一些建议。

下面是我如何分离第一个值的代码。我很感激任何关于如何解决这个问题的建议,谢谢!

char *kernel_input; 
char *end = NULL;
kernel_input = strtok(kArg, ":");
if(kernel_input == 0)
{
/* ERROR */
}
double value_1 = (double) strtod(kernel_input, &end);

您能不能试一下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARYSIZE 100                     // mamimum number of elements
/*
* show usage
*/
void
usage(char *cmd)
{
fprintf(stderr, "usage: %s -k value1:value2:..n", cmd);
}
/*
* split str, store the values in ary, then return the number of elements
*/
int
parsearg(double *ary, char *str)
{
char *tk;                           // each token
char *err;                          // invalid character in str
char delim[] = ":";                 // the delimiter
double d;                           // double value of the token
int n = 0;                          // counter of the elements
tk = strtok(str, delim);            // the first call to strtok()
while (tk != NULL) {                // loop over the tokens
d = strtod(tk, &err);           // extract the double value
if (*err != '') {             // *err should be a NUL character
fprintf(stderr, "Illegal character: %cn", *err);
exit(1);
} else if (n >= ARYSIZE) {      // #tokens exceeds the array
fprintf(stderr, "Buffer overflow (#elements should be <= %d)n", ARYSIZE);
exit(1);
} else {
ary[n++] = d;               // store the value in the array
}
tk = strtok(NULL, delim);       // get the next token (if any)
}
return n;                           // return the number of elements
}
int
main(int argc, char *argv[])
{
int i, n;
double ary[ARYSIZE];
if (argc != 3 || strcmp(argv[1], "-k") != 0) {
// validate the argument list
usage(argv[0]);
exit(1);
}
n = parsearg(ary, argv[2]);         // split the string into ary
for (i = 0; i < n; i++) {           // see the results
printf("[%d] = %fn", i, ary[i]);
}
}

如果执行编译后的命令,例如:

./a.out -k "0.0:-1.0:0.0:-1.0:4.0:-1.0:0.0:-1.0:0.0"

输出:

[0] = 0.000000
[1] = -1.000000
[2] = 0.000000
[3] = -1.000000
[4] = 4.000000
[5] = -1.000000
[6] = 0.000000
[7] = -1.000000
[8] = 0.000000

如果在字符串中放入一个无效字符,程序将打印一条错误消息并中止。

相关内容

最新更新