c++ 这个cout输出 为什么最后 不加endl 什么时候需要加 什么时候不需要 这个endl有什么作用?

c++ 这个cout输出 为什么最后 不加endl 什么时候需要加 什么时候不需要 这个endl有什么作用

img

加endl有换行的作用,所以当需要换行时可以在cout语句适合位置加个endl,如果不需要换行就不加endl。
测试代码如下:

参考链接:



#include <iostream>
using namespace std;

int main(void){
    
    int *ptr;
    ptr=new int;
    *ptr=10;
    cout<<*ptr;  // 这里没加endl,下面的输出会接着这里 
    // https://baike.baidu.com/item/endl/6256824?fr=aladdin
    cout<<"end"<<endl;  // 这里加了endl,会换行,下面的输出会另起一行再输出 
    cout<<"bye!";
    
    delete ptr;
    
    return 0;
} 
 

img