Wednesday, 15 May 2013

c++ strtok skips second token or consecutive delimiter -



c++ strtok skips second token or consecutive delimiter -

i trying read csv comma delimited file, content of file are

one,,three

and code read file this…

infile.getline(line, 500); token1 = strtok(line, ","); token2 = strtok(null, ","); token3 = strtok(null, ","); if(token1 != null){ cout << "token1 = " << token1 << "\n"; }else{ cout << "token1 = null\n" ; } if(token2 != null){ cout << "token2 = " << token2 << "\n"; }else{ cout << "token2 = null\n" ; } if(token3 != null){ cout << "token3 = " << token3 << "\n"; }else{ cout << "token3 = null\n"; }

output this

token1 = 1 token2 = 3 token3 = null

whereas expectation output should this…

token1 = 1 token2 = null token3 = 3

i did alter if statements

if(token1 != null)

to

if(token1)

but doesn’t works.

after checking illustration http://www.cplusplus.com/reference/cstring/strtok/, have updated

token2 = strtok(null, ",");

to

token2 = strtok(null, ",,");

as not works

once did face problem while reading csv comma delimited file. can utilize strtok() our solution in such problem delimited character appears consecutively. because according standard

the first phone call in sequence searches string pointed s1 first character not contained in current separator string pointed s2. if no such character found, there no tokens in string pointed s1 , strtok function returns null pointer. if such character found, start of first token. c11 §7.24.5.8 3

so, case did define solution using strpbrk() function useful you.

#include<iostream.h> char *strtok_new(char * string, char const * delimiter){ static char *source = null; char *p, *riturn = 0; if(string != null) source = string; if(source == null) homecoming null; if((p = strpbrk (source, delimiter)) != null) { *p = 0; riturn = source; source = ++p; } homecoming riturn; } int main(){ char string[] = "one,,three,"; char delimiter[] = ","; char * p = strtok_new(string, delimiter); while(p){ if(*p) cout << p << endl; else cout << "no data" << endl; p = strtok_new(null, delimiter); } system("pause"); homecoming 0; }

output

one no info 3

hope desired output.

c++ c

No comments:

Post a Comment