c++ - Why does this use of strtok() cause segmentation fault? -
i trying tokens in string using strtok()
, convert them integers. after getting 1 token, trying pull promptly segfaults - how tell system not segfault condition can complete?
code:
char * token; while ( getline (file,line) ) { char * charstarline = const_cast<char*>(line.c_str()); //cast charstar char * token; token = strtok(charstarline," "); token = strtok(charstarline," "); int inttoken = atoi(token); cout << "int token: " << inttoken << endl; while (token != null) { token = strtok (null, " "); int inttoken = atoi(token); cout << "int token (loop): " << inttoken << endl; }
is casting away const why segfaults? if how around this?
const
discussion aside, real problem;
while (token != null) // last token, not null { token = strtok (null, " "); // no more tokens makes go null here int inttoken = atoi(token); // , use null right away *boom* // before checking pointer. cout << "int token (loop): " << inttoken << endl; }
Comments
Post a Comment