简体   繁体   English

解析输入线c

[英]Parse an input line c

I want to extract some numbers from the input line which is a string. 我想从输入行中提取一些数字,这是一个字符串。 The string looks like this: 该字符串如下所示:

    command 1 2 3 4 5

So far i've done this but it is not working properly: 到目前为止,我已经做到了,但是不能正常工作:

   if ( strncmp(line,"command",7) == 0 ){
          char *p = strtok(line," ");
          while ( p !=NULL){
                param1 = atoi(p[1]);
                param2 = atoi(p[2]);
                param3 = atoi(p[3]);
                param4 = atoi(p[4]);
                param5 = atoi(p[5]);
                p = strtok(NULL," ");
          }
   }

Where am i wrong ? 我哪里错了?

Using sscanf might be simpler: 使用sscanf可能更简单:

if (strncmp(line, "command", 7) == 0)
{
    sscanf(&line[8], "%d %d %d %d %d", &param1, &param2, &param3, &param4, &param5);
}

Why do you &p[1] ? 你为什么&p [1]? p is a pointer to the current token in the while loop. p是while循环中指向当前令牌的指针。 It won't give you all the elements like you are expecting here. 它不会像您期望的那样为您提供所有元素。

You can declare param as an array: int param[5]; 您可以将param声明为数组:int param [5];

And rewrite the loop like: 并像这样重写循环:

    int i=0;
    while ( p !=NULL){
                    param[i++] = atoi(p);
                    p = strtok(NULL," ");
    }

If you want to use 5 variables like param1, param2....etc then you have to expand the loop and write it manually, not a good idea. 如果要使用5个变量,例如param1,param2 .... etc,则必须扩展循环并手动编写,这不是一个好主意。

#include <string.h>
int main(){
        char line[]="command 1 2 3 4 5";
       if ( strncmp(line,"command",7) == 0 ){
              char *p = strtok(line," ");        
              while ( p !=NULL){                
            printf("%s\n",p);
                    p = strtok(NULL," ");
              }
       }
    }

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

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