Using 'endl' in C++ programming

1.2k Views Asked by At
  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!

3

There are 3 best solutions below

1
On

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

enter image description here

0
On

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";
0
On

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