why this strtok doesn't work?
Hello,
This is a part of c code, which I used in a shell script to do the math.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
int main(int argc,char **argv){
char *tmp;
vector<float> input;
char in[128];
strcpy(in,argv[1]);
//cout << "arg # is " << argc << endl;
//cout << "arg[1] is " << in << endl;
tmp=strtok (in,"^");
input.push_back(atof(tmp));
cout << input[0] << "\t";
int i=1;
while( i<5 ){ // it is even worse if I use (tmp != NULL) or strcmp(tmp,NULL) here
tmp=strtok (NULL,"^");
i++;
cout << atof(tmp) << "\t";
//input.push_back(atof(tmp));
}
cout << endl;
return 0;
}
|
I used g++ to compile it because I used cout here just for convenience.
Below is the result:
./a.out 1^2^3^4^5
1 2 3 4 5
./a.out 1^2^3^4
Segmentation fault |
it seems that when strtok() comes to the last token part, it can't do it. I don't understand that is why.
Thanks for any enlightenment.
Last edited on
The problem is that you try to pass a null pointer to atof. You can simplify the program by using a for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int main(int argc,char **argv){
char *tmp;
char in[128];
strcpy(in,argv[1]);
for (tmp=strtok(in,"^"); tmp != NULL; tmp=strtok(NULL,"^")) {
cout << atof(tmp) << "\t";
}
cout << endl;
return 0;
}
|
Last edited on
Topic archived. No new replies allowed.