C++ cout gives undeclared identifier

冷暖自知 提交于 2019-12-01 17:11:15

问题


So, I have this question. Why does cout throws

error C2065: 'cout' : undeclared identifier

I am using Visual Studio 2012 as an IDE and I am writing a school project. I have everything done except an example file. So I am trying to write something on the screen like this:

#include "iostream"
#include "stdafx.h"
using namespace std;

int main()
{
    cout<<"example";

    return 0;
}

So the problem is with cout... printf works fine, but I want to use cout.

EDIT: I've changed "" to <> but it is not helping. Also I am using this code only for example... This is not the whole project.


回答1:


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.




回答2:


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;




回答3:


 #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.




回答4:


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.




回答5:


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?



来源:https://stackoverflow.com/questions/16858717/c-cout-gives-undeclared-identifier

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