C++ cout gives undeclared identifier

自作多情 提交于 2019-12-01 17:53:37
Matthieu Rouget

stdafx.h shall be the first include directive in your source file.

Switch files and convert the second include to <>, as other suggested.

#include "stdafx.h"
#include <iostream>

See this post for more information.

First of all:

#include <iostream>

instead of #include "iostream"

Secondly, it is generally considered bad practice to write using namespace std;, even though most courses start with that. It is better to only use what you actually need, in your case:

using std::cout;

taocp
 #include "iostream"

should be

 #include <iostream>

Quoting from this post:difference-between-iostream-and-iostream-quotes-in-include

By courtesy of @Jerry Coffin's answer:

When you use < >, the compiler only looks in the system-designated directory/directories (e.g., whatever you've set in the include environment variable) for the header.

When you use " ", the compiler looks in the local directory first, and if that fails, re-searches just like you'd used < >. Technically, (i.e., according to the standard) that doesn't have to be the "local" directory, but that's how it works in essentially every compiler of which I'm aware).

EDIT:

However, the root cause is that stdafx.h is a precompiled header. Visual C++ will not compile anything before the #include "stdafx.h" in the source file, unless the compile option /Yu'stdafx.h' is unchecked (by default); it assumes all code in the source up to and including that line is already compiled. However, it is still better to use <> with iostream not to confuse reader of the code.

If you use #include <iostream> with the <> instead of "" then it should work. Right now, the compiler doesn't know where to find the iostream library.

Also, you might want to change cout<<"example"; to cout<<"example"<<endl; for a new line so that it formats correctly.

This error also occurred in the Visual Studio 2017 IDE. Moving stdafx.h to the top solved the error.

For more on stdafx.h, see What's the use for "stdafx.h" in Visual Studio?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!