我有以下帶有 -k 引數的命令列界面,如下所示:-k "0.0:-1.0:0.0:-1.0:4.0:-1.0:0.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);
uj5u.com熱心網友回復:
請您嘗試以下操作:
#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 != '\0') { // *err should be a NUL character
fprintf(stderr, "Illegal character: %c\n", *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] = %f\n", 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
如果在字串中放入無效字符,程式將列印錯誤訊息并中止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322584.html
下一篇:為什么我的排序函式輸出垃圾值?
