oStream不显示概率C ++

ostream does not display proberly c++

本文关键字:概率 显示 oStream      更新时间:2023-10-16

我有一个项目,其中我使用人员目录。 在我的主课上,我将 cout <<my<<Directory 称为 endl;以显示此目录中人员的整个列表。 为此,我覆盖了目录类和 Person 类中的 <<运算符。

在目录类中,我出于特定原因使用地图,因此我以这种方式显示每个人:

 std::ostream& operator<<(std::ostream& os, const T& myDirectory)
{
  typedef map<Person, Location>::const_iterator Iterator;
  for(Iterator it=myDirectory.m_directory.begin();it!=myDirectory.m_directory.end;++it){
      os<<it->first<<endl;
}
return os;

为此,我还必须以这种方式重载 Person 类中的 <<运算符:

ostream& operator<<(std::ostream& os, const Person& p){
    os << p.lastName << "," << p.firstName << endl;
    return os;
}

我的问题是它没有正确显示。 逗号在姓氏和姓氏之前,名字和名字合并在一起。 例如,如果我的名字是杰克丹尼尔斯,我会在输出中得到这个:

,杰克尔斯

如果我使用 endl; 在姓氏和名字之后,它工作得很好。 例如:

os << p.lastName << endl;
os << "," << p.firstName << endl;

我得到这个输出:

丹尼尔斯
千斤顶

知道我做错了什么吗?

在这里

猜测,因为您没有提供完整的示例来说明问题,但我认为您会在姓氏末尾有一个尾随的"返回"字符。

它输出"Daniels"并将光标移回行首,然后用",Jack"覆盖它,因此输出将是",Jackls"

Endl 还会清理缓冲区。也许你应该添加out.flush()而不是endl,然后它会起作用吗?只是猜测。