Using strchr?

closed account (2NywAqkS)
In a winsock program, I'm making, the client recieves a stream of data that is then put into a char buffer[1024] the different parts of the stream are separated by a '.' so I imagine if it was using characters it would look like jarkfjn.hhfuiwyhklub.kayuh.fe.fhgkhg

How would I separate these chunks into there own arrays? I know strchr can get a character (in this case a '.'), but I'm not sure how to use it in this context.
I'm not sure if you're using c++ or C, Here is what I would do, but it is c++ only:

1
2
3
4
5
6
7
8
9
10
11
std::vector<std::string> data;
std::string word;

for (int i = 0; i < 1024; ++i)
{
    if (buffer[i] == NULL) break; // Define NULL as whatever will signal the end of the buffer
    if (buffer[i] == '.' && word.size() > 0)
        data.push_back(word), word.clear();
    else
        word += buffer[i];
}


Now you have a vector of all of the words. Access these like so:
1
2
for (std::vector<std::string>::iterator it = data.begin(); it != data.end(); ++it)
    std::cout << *it << ' ';


If your data isn't actually a set of strings, but is actually raw data, you can do:
1
2
3
4
5
6
7
8
9
10
11
12
typedef std::vector<char> dataword
std::vector<dataword> data;
dataword word

for (int i = 0; i < 1024; ++i)
{
    if (buffer[i] == NULL) break; // Define NULL as whatever will signal the end of the buffer
    if (buffer[i] == '.' && word.size() > 0)
        data.push_back(word), word.clear();
    else
        word.push_back(buffer[i]);
}
Last edited on
Topic archived. No new replies allowed.