|
| garrett (7) | ||||
| I have a string str="L1 L2 C1 P2 P1 S1 S2" and I would like to store each value into vectors. The following code is what I have attempted to do, when i run the file it crashes. I am almost sure my error is located in the line " obstypes[i]=p;" I attempted to use ".push_back" but i faced the same problem. Any suggestions would be gladly appreciated. Thanks, G
| ||||
| R0mai (196) | |||
| I strongly recomend using std::string's functions (find() and substr()) but Let's say you have to use c-style functions and c-style strings. then... Here are the problems in our code : 1. You don't include <cstring>, this header defines strtok and strcpy. 2. You make a varibale 'i' on line 14, altough you never use it. 3. You don't need a for loop here, you don't need to know how many tokens will be there. You have to test whether strtok() returns 0. 4. Before the loop you use strtok (line 22), and before you get the results out of p, in the first iteration you overwrite it again (line 33). Here is a corrected code :
EDIT : Always check out the reference for a function http://www.cplusplus.com/reference/clibrary/cstring/strtok/ There is an example very similar to yours. | |||
Last edited on | |||
| Bazzy (3164) | |
| The easiest way is using stringstreams | |
| garrett (7) | |
| Thanks alot for the help. I was actually using the "strtok" example and trying to implement vectors within it. I am new to C++ so i just experimenting with the functions. | |
| Duoas (2964) | |||
| You should avoid strtok() -- it modifies the argument string. If you use a stringstream, it would look something like:
Hope this helps. | |||
Registered users can post in this forum.
