tags:

views:

1848

answers:

4

I've got a function inside of a class that returns a string. Inside this function, I can only get it to work when I add cout<<endl to the function before the return statement. Any idea why this is, or how I can fix it? I'm running this in Eclipse on a Mac

In "main.cpp":

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include "Braid.h"
using namespace std;

static int size=3;

int main(){  
Braid * b1 = new Braid(size);
b1->setCanon();//creates canonical braid. 

cout<<"a ";
cout<<b1->getName()<<endl;
cout<<" b ";
}

In "Braid.h" :

  public:  
        Braid(int);  
        void setCanon();  
        string getName(); 
    };

And in "Braid.cpp":

string Braid::getName(){  
    string sName="";  

    /* body commented out
    for(int i=0; i<height; i++)
    {
     for(int j=2; j<(width-2); j++)
         {
             sName += boxes[i][j];
             sName += "|";
         }
        }

        */  
        //cout<<endl;
        return sName;
    }

When I run my main code, without the body of that function commented, the output I get is
"a 0|0|12|12|0|0|2|1|1|1|1|2|"

The "name" it returns is correct, but it's not making it past the function call. If I uncomment the //cout<<endl line, the function works and my output is
"a 0|0|12|12|0|0|2|1|1|1|1|2|
b "

After commenting out the body of the function, so that it only creates an empty string, and returns it, my output is only "a" then if I add the endl back, I get the "a b" that is expected.

What am I doing wrong? Is there something that comes with endl that I'm missing?

+12  A: 

actually getName() function is probably working correctly. However, the cout 'caches' the output (i.e. it prints the output on screen when it's internal text buffer is full). 'endl' flushes the buffer and forces cout to dump the text (in cache) to screen.

Try cout.flush() in main.cpp

Nitin Bhide
That did the trick. I guess cout doesn't work exactly like I thought. Anyway, Thanks!
Perchik
cout isn't really a print statement so much as somewhere to store an output.
contagious
+3  A: 

Maybe your terminal is lazy. Try omitting the endl and insert cout.flush() as the next line.

mdm
+2  A: 

cout should be flushed at program end.

fow@lapbert ~ % cat blah.cpp
#include <iostream>

int main() {
    std::cout << sizeof(int);
}
fow@lapbert ~ % ./a.out
4
fow
I've run into some old Sun Workstations that didn't, though.
mdm
A: 

It is very understandable thank you.

Agiew
Welcome to Stackoverflow.Stackoverflow is not a traditional forum. If you want to refer to an answer, please add your text as a comment instaed of a new post. It looks like an answer now.
kuester2000