Reputation: 5620
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?
Upvotes: 0
Views: 9620
Reputation: 566
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
Upvotes: 2
Reputation: 5584
Maybe your terminal is lazy. Try omitting the endl
and insert cout.flush(
) as the next line.
Upvotes: 3
Reputation: 1695
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
Upvotes: 12