C++中的endl搭配cout和cin用法
生活随笔
收集整理的這篇文章主要介紹了
C++中的endl搭配cout和cin用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
endl英語意思是end of line,即一行輸出結束,然后輸出下一行。
endl與cout搭配使用,意思是輸出結束。
按C++標準程序庫中的描述其實現如下:
template <class charT, class traits>
std::basic_ostream<charT, traits>&
std::endl (std::basic_ostream<charT, traits>& strm)
{
strm.put(strm.widen(\n'));
strm.flush();
return strm;
}
可見endl只是一個函數模板。
其主要搭配iostream對象來使用,如cout、cerr等,其作用是:
1.將換行符寫入輸出流,其中Unix/Linux換行符是\n,Windows中是\r\n,MAC中是\r;
2.清空輸出緩沖區。
在c++中如果使用輸入\輸出符endl。
比如在語句 :
cout<<"the id is"<<endl <<2;
cout<<"the id is"<<i << endl;
那么意思是:
endl就相當于輸出的時候回車。
第一句的輸出是:
the id is
2
第二句的輸出是:
the id is i
然后光標到了第二行。
額外的,還可以這樣使用endl:
std::endl(cout); // 等于 std::endl(std::cout);
std::endl(cout << "this id is" << i); // 等于 std::endl(std::cout << "this id is" << i);
(注:這是由于Koenig looup法則)
其中第一句等同于:std::cout << std::endl; // 不能寫成std::cout << endl;
第二句等于:std::cout << "this id is" << i << std::endl; // 如上所述
總結
以上是生活随笔為你收集整理的C++中的endl搭配cout和cin用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言入门之指针用法教程
- 下一篇: 夜考