C++ cout gives undeclared identifier

前端 未结 5 614
闹比i
闹比i 2021-01-18 11:33

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

相关标签:
5条回答
  • 2021-01-18 11:51

    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?

    0 讨论(0)
  • 2021-01-18 11:54

    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.

    0 讨论(0)
  • 2021-01-18 12:07
     #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.

    0 讨论(0)
  • 2021-01-18 12:11

    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;

    0 讨论(0)
  • 2021-01-18 12:11

    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.

    0 讨论(0)
提交回复
热议问题