简体   繁体   中英

Using 'endl' in C++ programming

  1. first code
#include <studio.h>

int main() {
    std::cout << "apple" << endl << "banana";
}
  1. second code
#include <iostream>
using namespace std;

int main(void) {
    cout << "apple" << endl;
    cout << "banana" << endl;
}

Why am i wrong? i know the answer is second one, But i want to know the why my first code is wrong. Please help me!

This first code is wrong because #include <studio.h> is the wrong header file. The correct header file for std::cout and std::endl is #include <iostream> .

It's also wrong because endl is in the std:: namespace. So even with the correct header file it should be std::endl

std::cout << "apple" << std::endl << "banana";

You forgot to put std:: before endl in the first case.

take a look at the doc: https://en.cppreference.com/w/cpp/io/manip/endl

as you can see, 2 important things are related to the error/question you posted:

  1. endl is defined in header <ostream>
  2. it is in the namespace std

so it must be used as std::endl note that the ostream is a parent of the iostream so including the iostream guaranties you have access to the ostream

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM