0

I have a value in character pointer variable and the value is changed dynamically.

for e.g

one case:
   char *ptr = sometext || abc.txt;

second case:
   char *ptr = abc.txt || sometext;

I need only file name in another variable. str = abc.txt

currently I am using the code:

CString str;
char* lpszToToken = stLine.GetBuffer(stLine.GetLength());
char* lpszToken = strtok(lpszToToken, "|");
while(lpszToken != NULL)
{
   lpszToken = strtok(NULL, "|");
   str = lpszToken;
}

but it working in only first case: I need a genric code to run in both case Any idea? Thanks,

suspectus
  • 16,548
  • 8
  • 49
  • 57
user2499879
  • 673
  • 3
  • 10
  • 16

2 Answers2

0

My C is rusty, but why not something like:

char* fname = strtok( fileNames, "|");
while (fname != NULL) {
    // do something with the file here..
    processFile( fname);             
    fname = strtok( NULL, "|");         // next.
}

Also, Hungarian notation is a horrible way to program. It effectively conceals & obfuscates most meaning, rendering clear and simple problems opaque & ugly. See how readable my example is, compared with the gack you supplied?

Your instructor (and Petzold) were very unfortunately mistaken to be teaching this to you. I suggest writing "literate" code instead.

See:

Community
  • 1
  • 1
Thomas W
  • 13,940
  • 4
  • 58
  • 76
  • @sasha.sochka Please provide a rationale/link for this kind of general statements. – arne Jul 15 '13 at 09:09
  • 1
    If my opinion was somewhere counted I would vote that `strtok` is the worst designed function for ever (in C) – sasha.sochka Jul 15 '13 at 09:10
  • I agree with Sasha. Hidden global state (worse than using global variables, since it is opaque), unclear API design & security issues. http://stackoverflow.com/questions/5999418/why-is-strtok-considered-unsafe But hey, I used it when I was a newbie too. – Thomas W Jul 15 '13 at 09:17
0

Since you have CString available you can use CString::Find or CString::Tokenize

ScottMcP-MVP
  • 10,337
  • 2
  • 15
  • 15