cout doesn't work after a while

Hi, I'm writing a program that separates strings. It needs to separate a string first by pipes ("|") and then by spaces. After the do-while loop which generates tokens delimited by pipes, the cout statement doesn't execute, but the system sleep statement does! I can't figure out why cout no longer works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

int main(int argc, char* argv[])
{
	char thestring[50];
	char delimiters_1[] = "|";
	char delimiters_2[] = " ";
	char *token, *cp, *firstpart;
	cout << "Please enter a string, then press RETURN: ";
	cin.get(thestring, 50);
	cp = thestring;
	cout << "Things separated by \"|\":\n";
	token = strtok(cp, delimiters_1);
	cout << token << endl;
	firstpart = token; //Will be used later
	do
	{
		token = strtok(NULL, delimiters_1);
		cout << token << endl << flush;
	}while(token != NULL);
	
	cout << "This is a test." << endl;
	system("sleep 5");
}


Lines 26 and 27 are there for debugging purposes only. Line 26 just seems to be ignored.
Last edited on
closed account (zb0S216C)
On line 22, the string must contain a '|' in order for the tokenizing to working; use the delimeters_2 instead( your choice though ).

Personally I would change to do...while to a while loop. do...while loops test their condition at the end of the loop, not before.

As for line 26, I'm still looking into it.
The program has to break down a command such as "ps -aux | more", so I am trying to get tokens delimited by pipes first. Later, I will use spaces as the delimiter to get "ps" and "-aux" (this is what the firstpart is going to be used for).

Thanks for the input on the while loop. I've changed that, since the do-while allowed a cout << NULL on its final pass.

Thanks for looking into line 26. I'm still baffled at how it can execute line 27 and not 26. It makes me think there is something wrong with cout, even though the buffer is flushed. The program is just terminating as if nothing is wrong.
Framework - I've solved the problem.

Even with a normal while loop, there was still a cout << NULL happening. This causes undefined behavior and prevents further cout << statements from functioning. I fixed it by writing the loop this way (I didn't know you could have an assignment occur inside the conditional):

1
2
3
4
	while((token = strtok(NULL, delimiters_1)) != NULL)
	{
		cout << token << endl;
	}


Thanks again for taking a look at this.
Topic archived. No new replies allowed.