2 Replies - 280 Views - Last Post: 07 August 2012 - 09:44 AM Rate Topic: -----

#1 DevonZ  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 73
  • Joined: 04-August 12

[Linux] System() Output Appears Before cout...

Posted 06 August 2012 - 08:16 AM

I'm trying to display a message using cout followed by system( "ls "). However, the console is showing the directory listing from system( "ls" ) before cout.

Any idea why this is happening and how I can correct it?

Code:
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	cout << "Directory listing before name change:\n";
	system( "ls -1Ap | grep -v /\\$" );
	
    return EXIT_SUCCESS;
}


Output:

Quote

Administrator@Administrator-LPC /cygdrive/c/Users/Administrator/Documents/C++/Directory Listing/Output/MingW
$ ./Directory\ Listing.exe
Directory Listing.exe
Directory listing before name change:


Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: [Linux] System() Output Appears Before cout...

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2102
  • View blog
  • Posts: 3,208
  • Joined: 21-June 11

Re: [Linux] System() Output Appears Before cout...

Posted 06 August 2012 - 08:41 AM

You need to flush the output buffer before you call system. You can either do that by calling cout.flush() or by using endl instead of "\n" to print a newline, which has the side-effect of flushing the stream.
Was This Post Helpful? 1
  • +
  • -

#3 vividexstance  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 656
  • View blog
  • Posts: 2,247
  • Joined: 31-December 10

Re: [Linux] System() Output Appears Before cout...

Posted 07 August 2012 - 09:44 AM

I'd just like to add that if you didn't need to write the new-line but you want to flush the stream. Then you could use flush function from the iomanip header.

Example:
// ...
#include <iomanip>
// ...
cout << "Hello, World!" << flush;

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1