我在一个返回字符串的类中有一个函数.在这个函数中,我只能cout<<endl 在return语句之前添加函数时才能使它工作 .知道为什么会这样,或者我如何解决它?我在Mac上用Eclipse运行它
在"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 ";
}
Run Code Online (Sandbox Code Playgroud)
在"Braid.h"中:
public:
Braid(int);
void setCanon();
string getName();
};
Run Code Online (Sandbox Code Playgroud)
在"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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的主代码时,没有注释该函数的主体,我得到的输出是
"a 0 | 0 | 12 | 12 | 0 | 0 | 2 | 1 | 1 | 1 | 1 | 2 |"
它返回的"名称"是正确的,但它没有通过函数调用.如果我取消注释该//cout<<endl行,该函数可以工作,我的输出是
"a 0 | 0 | 12 | 12 | 0 | 0 | 2 | 1 | 1 | 1 | 1 | 2 |
b"
在注释掉函数的主体后,它只创建一个空字符串,并返回它,我的输出只是"a"然后如果我添加endl,我得到预期的"a b".
我究竟做错了什么?有什么东西跟endl一样,我错过了吗?
Nit*_*ide 12
实际上getName()函数可能正常工作.但是,cout'缓存'输出(即当它的内部文本缓冲区已满时,它会在屏幕上打印输出).'endl'刷新缓冲区并强制cout将文本(在缓存中)转储到屏幕.
在main.cpp中尝试cout.flush()
| 归档时间: |
|
| 查看次数: |
9228 次 |
| 最近记录: |