I'm trying to assemble lexemes into one character array using concatenation, but some kind of nonsense comes out:

char str[80], str2[80]; scanf("%s", str); cout << "Разделение строки " << str << " на лексемы\n"; char * pch = strtok(str, "Cc"); for (int i=0; pch != NULL; i++) { cout << pch << endl; strcat(str2, pch); pch = strtok(NULL, "Cc"); } strcat(str2, "\0"); system("pause"); return 0; 
  • I think few people know what it means to "lexemes". Give an example of what you want to get and what you get at the output. - nick_n_a

1 answer 1

You must initialize the str2 array with the string

 str2[80]; str2[0] = '\0'; 

before performing concatenation.

And this offer

 strcat(str2, "\0"); 

can be removed as unnecessary.

Also in this loop, the variable i not used.

 for (int i=0; pch != NULL; i++) 

Therefore, it would be better to declare a cycle as

 while ( pch ) 
  • Will tokens be added after before \ 0 or do you need to do strrev? - losty
  • @losty strcat appends a new line to the end of the current line. - Vlad from Moscow