You are here:

C++/C++ cout stops working

Advertisement


Question
I wrote a program that seems to compile and work fine, except that after a do-while loop completes, "cout" no longer does anything. I've tried using cout << flush; and I've added a system("sleep 3"); statement after the cout in question, for debugging purposes. The sleep executes, but the cout still prints nothing!

Here is the code:

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;
  printf("Test");
  system("sleep 3");
}

Answer
Hello Ben

Notice in this loop

do
   {
       token = strtok(NULL, delimiters_1);
       cout << token << endl << flush;
   }while(token != NULL);

the final token, which will cause the loop to exit will be NULL,but cout is being used to print out even that token. That is probably terminating your program which is why you don't see later couts or prints.

Here is a better way of organizing the loop

#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
   char thestring[50];
   char delimiters_1[] = "|";
   char delimiters_2[] = " ";

/* In my opinion, it is good to initialize your automatic variables */
   char *token = NULL;
   char *cp = NULL;
   char *firstpart = NULL;

   cout << "Please enter a string, then press RETURN: ";
   cin.get(thestring, 50);
   cp = thestring;

   cout << "Things separated by \"|\":\n";
   token = strtok(cp, delimiters_1);
   while(token != NULL)
   {
       firstpart = token; //Will be used later
       cout << token << endl;
       token = strtok(NULL, delimiters_1);
   }
   cout << "This is a test." << endl;
}

Notice that even the first strtok result (before the loop) now gets checked for NULL. I don't know how firstpart will be used, so I cannot comment on that further, but you should initialize it to NULL when being declared.

I hope that helps.

Best regards
Zlatko

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2016 About.com. All rights reserved.