If I understand it correctly, strtok scans from the first character after the separator. The code below:
gives an output like this:
arule
12
brule
21
zrule
70
drule
25
erule
10
However, if I remove the space between " and (arule, 12) so the line would look like:
then the output would become:
brule
21
zrule
70
drule
25
erule
10
Why is a space needed between " and the first separator in order for the program to work correctly? Am I doing something incorrectly?
Code:
#include <iostream> #include <fstream> using namespace std; void main() { char *rules[50]; int priority[50]; int i=0; char line[100]=" (arule, 12), (brule, 21), (zrule, 70), (drule, 25), (erule, 10)(frule, 3)(grule, 20), (srule, 100)"; char *tok = strtok(line,"("); rules[i]=strtok(NULL,","); tok=strtok(NULL,")"); priority[i]=atoi(tok); i++; while((tok=strtok(NULL,"("))!=NULL) { rules[i]=strtok(NULL,","); tok=strtok(NULL,")"); priority[i]=atoi(tok); i++; } for(int j=0;j<i;j++) { cout<<rules[j]<<endl; cout<<priority[j]<<endl; } }
arule
12
brule
21
zrule
70
drule
25
erule
10
However, if I remove the space between " and (arule, 12) so the line would look like:
Code:
char line[100]="(arule, 12), (brule, 21), (zrule, 70), (drule, 25), (erule, 10)(frule, 3)(grule, 20), (srule, 100)"; //there's no space between " and (arule, 12)
brule
21
zrule
70
drule
25
erule
10
Why is a space needed between " and the first separator in order for the program to work correctly? Am I doing something incorrectly?
Comment