[英]Using 'endl' in C++ programming
#include <studio.h>
int main() {
std::cout << "apple" << endl << "banana";
}
#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::cout
和std::endl
的正确 header 文件是#include <iostream>
。
It's also wrong because endl
is in the std::
namespace.这也是错误的,因为
endl
在std::
命名空间中。 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:如您所见,有两件重要的事情与您发布的错误/问题有关:
endl
is defined in header <ostream>
endl
在 header <ostream>
中定义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.