Misbehaving program

Hi, I'm having a little trouble with this program. I can't figure out why it's wrong.

Here is the original code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char the_string[81], *p;
    cout << "Input a string to parse: ";
    cin.getline(the_string, 81);
    p = strtok(the_string, ", ");
    while (p != NULL) {
        cout << p << endl;
        p = strtok(NULL, ", ");
    }
    system("PAUSE");
    return 0;
}


This is copied exactly as it appears in the book. But it doesn't separate the tokens based on a comma and space", " like I pass to the strtok function, it uses just spaces instead. I have no idea why that is.

Then I was given an exercise to modify this program so that it prints how many tokens it finds. This was simple.

The next exercise however, wants me to rebuild the string from the tokens, and separate them with &'s. I have made an attempt which to me seems like it should work, but it causes the program to crash after it has displayed the tokens. Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    unsigned short int count = 0;
    char the_string[81], rebuilt_string[81], *p;
    cin.getline(the_string, 81);
    p = strtok(the_string, ", ");
    while (p != NULL)   {
        cout << p << endl;
        p = strtok(NULL, ", ");
        strcat(rebuilt_string, p);
        strcat(rebuilt_string, "&");
        count++;
    }

    cout << "A total of " << count << " tokens were found." << endl;

    cout << "Here is the string rebuilt: " << rebuilt_string << endl;

    return 0;
}


So why does this baby crash and burn?
strcat(rebuilt_string, p);

p is NULL.
Thanks moschops, however there are still two problems with this program.

First is the tokens are seperated by spaces even though I explicitly told it to cut them at a comma and a space;", ".

The second is that when the program rebuilds the string and prints it garbage is displayed.

Anyone know what's wrong?
Someone's gotta know right?
First is the tokens are seperated by spaces even though I explicitly told it to cut them at a comma and a space;", ".

A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters. http://cplusplus.com/reference/clibrary/cstring/strtok/
You may use strstr instead.

The second is that when the program rebuilds the string and prints it garbage is displayed.
You didn't initialize 'rebuilt_string'
I didn't initialize the_string either. Did the cin operation initialize it?

How would I initialize rebuilt_string? Set it to "a" or something?
Topic archived. No new replies allowed.