简体   繁体   English

在C函数中使用令牌(strtok)的值

[英]Use value of token (strtok) in function in c

I got a bit confused using token, say if: 我对使用令牌有些困惑,说:

int main(void) {
    char input[100];
    fgets(input, 100, stdin);
    char * token = strtok(input, " ");
    char * height = strtok(NULL, " ");
    char * width = strtok(NULL, " ");
    if (height > 9 && width > 9)
        set(height, width);
}

void set(char * height, char * width) {
    for (int i = 0; i < height + 1; i++) {
        for (int j = 0; j < width + 1; j++) {
            mine[i][j] = '*';
        }
    }
}

I just found that i can't use "height+1", can anyone tell me any way to use the value of height? 我只是发现我不能使用“ height + 1”,有人可以告诉我任何使用高度值的方法吗? Besides, should i put char *height and char *width in void set? 此外,我应该将char * height和char * width放入void集吗?

Thanks! 谢谢!

strtok() cuts the c-string into pieces and returns pointers to the delimited substrings. strtok()将C字符串切成小段,并返回指向分隔的子字符串的指针。

So with your code, if you enter "480 640", the pointer height will point to "480" and the pointer width to "640". 因此,对于您的代码,如果输入“ 480 640”,则指针height将指向“ 480”,指针width将指向“ 640”。 So they point to (ascii) strings not to integers. 因此,它们指向(ascii)字符串而不是整数。

If you need integers, you first have to convert them, for example with atoi() : 如果需要整数,则首先必须将它们转换,例如使用atoi()

int main(void){
  ...
  char *token=strtok(input, " ");
  char *s_height=strtok(NULL, " "); // these are strings
  char *s_width=strtok(NULL, " ");
  int height=atoi(s_height), width=atoi(s_width); // convert to integers
  ... 
}

void set(int height, int width){
  ...
}  

After reading from your stream with fgets() and tokenizing it, you should convert your strings into the appropriate integer values. 使用fgets()从流中读取并标记化之后,应将字符串转换为适当的整数值。

char *heightStr = strtok(NULL, " ");
char *widthStr = strtok(NULL, " ");
int heightVal = atoi(heightStr);
int widthVal = atoi(widthStr);

Your set() function should also use integers as it's parameter types, not char* ie. 您的set()函数还应该使用整数作为参数类型,而不是char*即。 void set(int height, int width)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM