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:
if (strncmp(line, "command", 7) == 0)
{
sscanf(&line[8], "%d %d %d %d %d", ¶m1, ¶m2, ¶m3, ¶m4, ¶m5);
}
Why do you &p[1] ? p is a pointer to the current token in the while loop. It won't give you all the elements like you are expecting here.
You can declare param as an array: 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.
#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," ");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.