简体   繁体   English

在 C++ 编程中使用“endl”

[英]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.第一个代码是错误的,因为#include <studio.h>是错误的 header 文件。 The correct header file for std::cout and std::endl is #include <iostream> . std::coutstd::endl的正确 header 文件是#include <iostream>

It's also wrong because endl is in the std:: namespace.这也是错误的,因为endlstd::命名空间中。 So even with the correct header file it should be std::endl因此,即使使用正确的 header 文件,它也应该是std::endl

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

You forgot to put std:: before endl in the first case.在第一种情况下,您忘记将std::放在endl之前。

take a look at the doc: https://en.cppreference.com/w/cpp/io/manip/endl看看文档: 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> endl在 header <ostream>中定义
  2. it is in the namespace std它在命名空间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所以它必须用作std::endl请注意,ostream 是 iostream 的父级,因此包括 iostream 保证您可以访问 ostream

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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