C++ 返回字符串的函数不起作用,除非涉及 endl...?
我在类中有一个返回字符串的函数。 在这个函数中,只有在 return 语句之前将 cout<
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;
}
当我运行我的主代码时,没有注释该函数的主体,输出我得到的是
"a 0|0|12|12|0|0|2|1|1|1|1|2|"
它返回的“名称”是正确的,但它没有超过函数调用。 如果我取消注释 //cout<
“0|0|12|12|0|0|2|1|1|1|1|2|
b "
注释掉函数体后,它只创建一个空字符串并返回它,我的输出只有“a”,然后如果我添加 endl 回来,我会得到“a b” 我做错了什么
吗?我缺少什么东西吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,getName() 函数可能工作正常。 但是,cout 会“缓存”输出(即,当内部文本缓冲区已满时,它会在屏幕上打印输出)。 'endl' 刷新缓冲区并强制 cout 将文本(在缓存中)转储到屏幕。
尝试 main.cpp 中的 cout.flush()
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
也许你的终端很懒。 尝试省略
endl
并插入cout.flush(
) 作为下一行。Maybe your terminal is lazy. Try omitting the
endl
and insertcout.flush(
) as the next line.cout
应该在程序结束时刷新。cout
should be flushed at program end.