c++中endl和\n的区别

平常在使用的时候,如果程序不复杂,其实endl和\n在使用效果上没有什么区别,实际上,作为一个流操作符,endl比起\n多了一项功能,那就是刷新输出缓冲区。

从简单的平时使用来看

我们平时使用的:

std::cout<<std::endl;

可以简单的理解为:

std::cout << '\n' << std::flush

使用cout代替\n的好处是,由于输出流缓冲区在被填满的时候会自动刷新输出,可能会造成不必要的输出麻烦。但其实普通的cout相对于文件输出流而言,其实并没有太大必要使用endl。

很明显,endl是给具有缓冲区的流设计的,像cerr这样的无缓冲流就不用\n换行了。

从endl的源代码来看

endl包含在ostream库当中
利用搜索功能我们可以找到如下源代码

/**
   *  @brief  Write a newline and flush the stream.
   *
   *  This manipulator is often mistakenly used when a simple newline is
   *  desired, leading to poor buffering performance.  See
   *  https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html#io.streambuf.buffering
   *  for more on this subject.
  */
  template<typename _CharT, typename _Traits>
    inline basic_ostream<_CharT, _Traits>&
    endl(basic_ostream<_CharT, _Traits>& __os)
    { return flush(__os.put(__os.widen('\n'))); }

可见endl实际是名字空间std中的一个全局内联函数(记住std::endl是一个函数),它做了两件事:

  1. 输出一个换行符
  2. 调用flush。
    再看看flush
/**

 *  @brief  Flushes the output stream.

 *

 *  This manipulator simply calls the stream's @c flush() member function.

*/

template<typename _CharT, typename _Traits>

inline basic_ostream<_CharT, _Traits>&

flush(basic_ostream<_CharT, _Traits>& __os)

{

  return __os.flush(); // 注意这里的os不是操作系统的意思,而是类basic_ostream的缩写

}

这里的flush是std::basic_ostream::flush

/**

 *  @file  ostream.tcc

*/

template<typename _CharT, typename _Traits>

basic_ostream<_CharT, _Traits>&

basic_ostream<_CharT, _Traits>::flush()

{

  // _GLIBCXX_RESOLVE_LIB_DEFECTS

  // DR 60. What is a formatted input function?

  // basic_ostream::flush() is *not* an unformatted output function.

  ios_base::iostate __err = ios_base::goodbit;

 

  __try

  {

    // 刷新发生在pubsync,底层调用的是LIBC库函数fflush

    if (this->rdbuf() && this->rdbuf()->pubsync() == -1)

      __err |= ios_base::badbit;

  }

  __catch(__cxxabiv1::__forced_unwind&)

  {

    this->_M_setstate(ios_base::badbit);

    __throw_exception_again;

  }

  __catch(...)

  {

    this->_M_setstate(ios_base::badbit);

  }

  if (__err)

    this->setstate(__err);

  return *this;

}

便是整个endl操作符的机理。

tips:“cout” is pronounced “see-out” The "c stands for “character” because iostreams map values to and from byte (char) representations.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值