[英]use of strsep in C while parsing argv Variable doesen't work
I have a problem in C while parsing the argv Variable. 我在解析argv变量时遇到了C问题。 This is the task: 这是任务:
I got some Parameters form the Command line into my C programm. 我从命令行将一些参数输入到C程序中。 One of them looks like "-r=20-5". 其中之一看起来像“ -r = 20-5”。 There I have to find the "r". 在这里,我必须找到“ r”。 this works with: 这适用于:
if (argv[i][0] != 0 && argv[i][1] != 0 && argv[i][2] != 0 &&
argv[i][0] == '-' && argv[i][2] == '=') { /* Check the Variables */
switch (argv[i][1]) {
case 'r':
/* what have to be here? */
break;
}
Now I have the "r". 现在我有了“ r”。 But I need the 20 and the 5 in two different variables too. 但是我也需要两个不同的变量中的20和5。 Here is what i thougt about, but it did't work. 这就是我想要的,但是没有用。 I tried something with 我尝试过
strsep(argv[i]+3, "-");
But my Compiler (Xcode) throws a warning (warning: passing argument 1 of 'strsep' from incompatible pointer type) 但是我的编译器(Xcode)发出警告(警告:从不兼容的指针类型传递'strsep'的参数1)
Does anyone has any idea (or link) how I can solve the problem? 有谁知道(或链接)我如何解决问题?
After it's solved there was still a warning, so I was answered to post my entire new code: 解决之后,仍然会有警告,所以我被要求张贴我的整个新代码:
int parse(int argc, const char *argv[]) {
int i, x, y;
int intTmp;
long longTmp;
char *strTmp;
char *end;
for (i = 1; i < argc; i++) {
/* check for (-?=) */
if (argv[i][0] != 0 && argv[i][1] != 0 && argv[i][2] != 0 &&
argv[i][0] == '-' && argv[i][2] == '=') {
/* IGNORE THIS
* longTmp = strtol(argv[i]+3, &end, 10);
* intTmp = analyseEndptr(longTmp, argv[i]+3, end);
*/
switch (argv[i][1]) {
case 'r':
strTmp = argv[i]+3; /* <= Here I got the warning */
x = atoi(strsep(&strTmp, "-"));
y = atoi(strsep(&strTmp, "-"));
printf("x=%d, y=%d\n", x, y);
break;
}
}
}
}
The warning is: warning: passing argument 1 of 'strsep' from incompatible pointer type 警告是:警告:从不兼容的指针类型传递'strsep'的参数1
My compiler is: gcc on MacOS using XCode as IDE 我的编译器是:在MacOS上使用XCode作为IDE的gcc
Do you know sscanf? 你知道sscanf吗? Have a look at: 看一下:
unsigned a,b;
if( 2==sscanf(argv[i],"-r=%u-%u",&a,&b) )
printf("%u-%u",a,b);
Here is how you pass a string to strsep()
这是将字符串传递给strsep()
switch (argv[i][1]) {
char *s;
int x, y;
case 'r':
s = argv[i] + 3;
x = atoi(strsep(&s, "-"));
y = atoi(strsep(&s, "-"));
printf("x=%d, y=%d\n", x, y);
break;
}
Will produce: 将产生:
x=3, y=4
Do not use it as is. 不要按原样使用它。 You will have to do additional NULL
checks on x
and y
appropriately for your case. 您将必须根据情况适当地对x
和y
进行其他NULL
检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.