Ошибка visual studio c2065

They most often come from forgetting to include the header file that contains the function declaration, for example, this program will give an ‘undeclared identifier’ error:

Missing header

int main() {
    std::cout << "Hello world!" << std::endl;
    return 0;
}

To fix it, we must include the header:

#include <iostream>
int main() {
    std::cout << "Hello world!" << std::endl;
    return 0;
}

If you wrote the header and included it correctly, the header may contain the wrong include guard.

To read more, see http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.

Misspelled variable

Another common source of beginner’s error occur when you misspelled a variable:

int main() {
    int aComplicatedName;
    AComplicatedName = 1;  /* mind the uppercase A */
    return 0;
}

Incorrect scope

For example, this code would give an error, because you need to use std::string:

#include <string>

int main() {
    std::string s1 = "Hello"; // Correct.
    string s2 = "world"; // WRONG - would give error.
}

Use before declaration

void f() { g(); }
void g() { }

g has not been declared before its first use. To fix it, either move the definition of g before f:

void g() { }
void f() { g(); }

Or add a declaration of g before f:

void g(); // declaration
void f() { g(); }
void g() { } // definition

stdafx.h not on top (VS-specific)

This is Visual Studio-specific. In VS, you need to add #include "stdafx.h" before any code. Code before it is ignored by the compiler, so if you have this:

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

The #include <iostream> would be ignored. You need to move it below:

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

Feel free to edit this answer.

I ran across this error after just having installed vs 2010 and just trying to get a nearly identical program to work.

I’ve done vanilla C coding on unix-style boxes before, decided I’d play with this a bit myself.

The first program I tried was:

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World!";
    return 0;
}

The big thing to notice here… if you’ve EVER done any C coding,

int _tmain(int argc, _TCHAR* argv[])

Looks weird. it should be:

int main( int argc, char ** argv )

In my case I just changed the program to:

#include <iostream>
using namespace std;

int main()
{
     cout << "Hello world from  VS 2010!n";
     return 0;
}

And it worked fine.

Note: Use CTRL + F5 so that the console window sticks around so you can see the results.

  • Remove From My Forums
  • Question

  • Im having trouble building a programme when i do it fails and says this:

    error C2065: ‘cout’ : undeclared identifier

    I built a programme before using «cout» which works fine called test here it is

    /*
    this is a test
    */
     #include «StdAfx.h»

    #include <iostream>
    using namespace std;

    int main()
    {
     cout << «hi this is a test «

     
     ;system («pause»);

      ;return 0;
    }

    that one works well it is a CLR console application.

    i am using microsoft visual basic 2010

    the programme that doesnt work and gets the error

    error C2065: ‘cout’ : undeclared identifier

    i think is a win32 application

    i am new to C++ and have just started learning,can anyone help?

Answers

  • Hi,

    In Visual Studio there are two kinds of *.exe binaries, windows applications and console applications. A console application is has a single console window where all input, output and errors are displayed. While a windows application usually presents a window
    and interacts with the user using the Microsoft GUI.

    For developers, the main difference between Windows Applications and Console Applications is that the former’s entry point is WinMain() or wWinMain(), while the latter’s entry point is main() or wmain().

    We can use cout in console applications to output strings to the console window. While in Windows applications, cout cannot be used and we can use other APIs such as TextOut instead to output on the window.

    So please separate console applications from windows applications. It is not proper for us to mix the two types of applications together.

    I hope this reply is helpful to you.
    Best regards,


    Helen Zhao [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by

      Monday, November 28, 2011 9:03 PM

In this tutorial, we will learn about the compiler error C2065 in C++. We look at possible reasons for this error and their corresponding solutions.

The error message displayed for C2065 is:

identifier‘: undeclared identifier

This means that there is some issue with the code and that the compiler is unable to compile the code until this is fixed.

Compiler Error C2065 in C++

Identifiers are the names we give variables or functions in our C++ program. We get the error C2065 when we use such identifiers without first declaring them. Sometimes we may think that we have declared these identifiers, but there is a chance that we have not done so properly. I have shown a simple example below where we get the C2065 error message while compiling the code.

int main()
{
  // uncommenting the following line removes the error
  // int i;

  i = 5;
  return 0;
}

This is because we are using the variable ‘i’ without first declaring it.

The following sections have some common reasons and solutions for the C2065 error message.

Identifier is misspelt

This is a very common mistake that we all make. Sometimes we type the identifier wrong which results in the C2065 error message. Here are a few examples.

int main()
{
  int DOB;
  int students[50];
  
  dob = 32; // we declared 'DOB' but used 'dob'
  student[0] = 437; // we declared 'students' but used 'student'

  return 0;
}

Identifier is unscoped

We must only use identifiers that are properly scoped. In the example given below, we declare ‘a’ inside the ‘if‘ statement. As a result, its scope is restricted to that ‘if‘ block.

int main()
{
  int n = 5;

  if (n > 3)
  {
    int a = 3;
    a++;
  }
  
  // a cannot be used outside its scope
  a = 5;

  return 0;
}

We must also bring library functions and operators into the current scope. A very common example of this is the ‘cout‘ statement which is defined in the ‘std‘ namespace. The following code results in the C2065 error.

#include <iostream>

int main()
{
  cout << "Hello World";

  return 0;
}

This error can be removed by either of the following methods.

#include <iostream>

int main()
{
  // we fully qualify the identifier using the 
  // reuired namespace 
  std::cout << "Hello World";

  return 0;
}

or

#include <iostream>

// we bring the std namespace into the scope
using namespace std;

int main()
{
  cout << "Hello World";

  return 0;
}

Precompiled header is not first

Let us say we have a precompiled header file. All other preprocessor directives must be put after the #include statement of the precompiled header. Thus, the following code having the precompiled header “pch.h” results in a C2065 error.

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

using namespace std;

int main()
{
  cout << "Hello World";

  return 0;
}

We can fix this by moving the including of pch.h to the top as shown below.

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

using namespace std;

int main()
{
  cout << "Hello World";

  return 0;
}

The necessary header file is not included

We need to include header files if we are to use certain identifiers. We see the C2065 error message in the following code as we need to include the string header to use objects of string type.

// Uncomment the following line for the code to work
// #include <string>

using namespace std;

int main()
{
  string s;

  return 0;
}

The closing quote is missing

We need to properly close quotes for the code to work correctly. In the example given below, the C2065 error shows up because the compiler does not properly recognise ‘d’.

int main()
{
  // we need a closing quote (") after 'dog' in the following line
  char c[] = "dog, d[] = "cat";

  d[0] = 'b';

  return 0;
}

Conclusion

In this tutorial, we looked at some possible reasons for the compiler error C2065 in C++. We also learnt about possible solutions. We may obtain this message for other reasons. Here is the link to Microsoft’s documentation for the C2065 error in Visual Studio 2019.

yk92

0 / 0 / 2

Регистрация: 28.02.2010

Сообщений: 35

1

07.11.2010, 20:35. Показов 109634. Ответов 35

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

видаёт мне такую ошибку:
1>c:documents and settingsадминистратор.home-8a34687735мои документыvisual studio 2010projectslab 1.3lab 1.3lab 1.3.cpp(41): error C2065: cout: необъявленный идентификато
ето для cin, cout u endl.
Подскажите что делать
вот текст програми

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
 
#include "StdAfx.h"
using namespace std;
 
int main (void)
{
int massiv[5];
int min;
int srednee;
for(int i=0;i<5;i++)
{
cin>>massiv[i];
}
_asm 
{
lea esi,massiv;
mov ecx,5;
mov edx,[esi];
xor edi,edi;
 
cikl: mov ebx,[esi];
      add edi,ebx;
      cmp ebx,edx;
      jg lab1;
      mov edx,ebx;
lab1:
      dec ecx;
      add esi,4;
      cmp ecx,0;
      jnz cikl;
      mov min,edx;
      mov srednee,edi;
 
}
for(int i=0;i<5;i++)
{
cout<<massiv[i]<<" ";
}
cout<<endl<<"MIN->"<<min<<endl;
cout<<"Tselaya chast ot Srednego arifmeticheskogo->"<<srednee/5;
getchar();
getchar();
return(0);
}



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

07.11.2010, 20:35

35

Ignat

1260 / 798 / 108

Регистрация: 16.09.2009

Сообщений: 2,010

07.11.2010, 22:38

2

Надо сначала подключить Stdafx, а уже потом iostream, короче говоря поменять местами строки.

C++
1
2
#include "stdafx.h"
#include <iostream>



6



vaselo

19 / 19 / 5

Регистрация: 17.10.2010

Сообщений: 247

07.11.2010, 23:40

3

C++
1
2
3
4
5
6
7
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
 
using std::cout;
using std::cin;
using std::endl;

в вижуале он почему-то требует вот такого описания. Может ты еще и фигурную скобку не открыл?



0



M128K145

Эксперт JavaЭксперт С++

8381 / 3613 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

08.11.2010, 11:02

4

vaselo, уже есть

C++
1
using namespace std;

а избыточность ни к чему. Правильный ответ во втором посте



0



Antariya

0 / 0 / 0

Регистрация: 08.06.2011

Сообщений: 4

08.06.2011, 23:23

5

А что делать в 10й висуал студо(экспресс)?
Та же ошибка:
error C2065: endl: необъявленный идентификатор
error C2065: end: необъявленный идентификатор.
Добавление строчки:

C++
1
using namespace std;

не помогает.

(Либерти, упражнение 2, день 1)

C++
1
2
3
4
5
6
7
8
9
10
11
12
#include "stdafx.h"
#include <iostream>
 
int _tmain(int argc, _TCHAR* argv[])
{
    int x = 5;
    int y = 7;
    std::cout << endl;
    std::cout << x + y << " " << x * y;
    std::cout << end;
    return 0;
}



0



593 / 531 / 76

Регистрация: 22.03.2011

Сообщений: 1,585

08.06.2011, 23:43

6

Antariya,
std::endl;
+ опечатка в 10 строке

Цитата
Сообщение от Antariya
Посмотреть сообщение

не помогает.

а вот это странно



0



Эксперт JavaЭксперт С++

8381 / 3613 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

09.06.2011, 00:13

7

Antariya, а мне кажется, что кто-то пытается нас обмануть. При том коде, который сейчас должны вылетать две ошибки:
error C2065: endl: необъявленный идентификатор
error C2065: end: необъявленный идентификатор.
при добавлении юзинга должна вылетать только одна ошибка
error C2065: end: необъявленный идентификатор.



0



0 / 0 / 0

Регистрация: 08.06.2011

Сообщений: 4

09.06.2011, 12:40

8

OstapBender, именно как в книге написала. Попробовала исправить.
Ошибки:
warning C4067: непредвиденные лексемы за директивой препроцессора, требуется newline
warning C4551: в вызове функции отсутствует список аргументов
error C2568: идентификатор: не удается разрешить перегрузку функции
warning C4551: в вызове функции отсутствует список аргументов
M128K145, если бы обманывала. Только начала изучение, имела дело только с бейсиком в школе.



0



3364 / 2620 / 322

Регистрация: 11.03.2009

Сообщений: 5,966

09.06.2011, 12:49

9

Таки сложно следить за изменениями, было бы лучше выкладывать текуший вариант программы вместе с его ошибками.



0



Antariya

0 / 0 / 0

Регистрация: 08.06.2011

Сообщений: 4

09.06.2011, 12:51

10

kazak, А. Точно. Извиняюсь.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// day.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>;
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
        int x = 5;
        int y = 7;
        std::endl;
        std::cout << x + y << " " << x * y;
        std::end;
        return 0;
}

warning C4067: непредвиденные лексемы за директивой препроцессора, требуется newline
warning C4551: в вызове функции отсутствует список аргументов
error C2568: идентификатор: не удается разрешить перегрузку функции
warning C4551: в вызове функции отсутствует список аргументов



0



diagon

Higher

1953 / 1219 / 120

Регистрация: 02.05.2010

Сообщений: 2,925

Записей в блоге: 2

09.06.2011, 12:53

11

C++
1
2
3
4
5
6
7
8
9
10
11
#include "stdafx.h"
#include <iostream>
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
        int x = 5;
        int y = 7;
        cout << endl <<  x + y << " " << x * y << endl;
        return 0;
}

После #include <iostream> не надо точку с запятой
если пишите using namespace std; то нет смысла писать std::
endl нужно использовать прямо в потоке.
end- непонятно что такое, видимо опечатка в endl



1



kazak

3364 / 2620 / 322

Регистрация: 11.03.2009

Сообщений: 5,966

09.06.2011, 12:54

12

Цитата
Сообщение от Antariya
Посмотреть сообщение

C++
1
2
3
std::endl;
 std::cout << x + y << " " << x * y;
 std::end;

endl в отдельности не используется, end вообще не существует.

C++
1
2
3
std::cout << std::endl;
 std::cout << x + y << " " << x * y;
 std::cout << std::endl;



1



0 / 0 / 0

Регистрация: 08.06.2011

Сообщений: 4

09.06.2011, 13:44

13

kazak, diagon, всё получилось, огромное спасибо.



0



Oleg35

0 / 0 / 0

Регистрация: 26.01.2011

Сообщений: 8

30.10.2012, 19:41

14

Здравствуйте, а можете мне помочь?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "stdafx.h"
#include <iostream>
 
int main()
{
    int a, b;
    char op; //operator
    int res; //result
 
    cout << "Enter expression ";
    cin >> a;
    cin >> op;
    cin >> b;
 
    if (op== '+')
        res = a+b;
    else if (op == '-')
        res = a-b;
    else if (op == '*')
        res = a*b;
    else if (op == '/')
        res = a/b;
    else
    {   cout << "Bad operator";
        return 0;
    }
        
    
    cout << "Result = ";
    cout << res;
    cout << end;
    
    return 0;
}

выдает (при отладке)

Error C2065: cout: необъявленный идентификатор

(Урок 2- http://data.com1.ru/prog-schoo… esson2.mp4

Visual 08-Упрощенная(тоесть только для C++)



0



M128K145

Эксперт JavaЭксперт С++

8381 / 3613 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

30.10.2012, 20:56

15

Oleg35, используйте std::cout, std::cin и std::endl или после инклудов напишите

C++
1
using namespace std;

Первый вариант предпочтительнее



0



Мой лучший друг-отладчик!

167 / 167 / 30

Регистрация: 24.06.2012

Сообщений: 662

Записей в блоге: 5

30.10.2012, 22:09

16

M128K145, в ходе обучения использование using namespace std; вместо std:: способствует, как мне кажется, лучшему восприятию кода.И на ранних этапах обучения программированию использвание пространства предпочтительнее.

Но с другой стороны, в профессиональном программировании, насколько я знаю, юзать нужно только std::.Мне тут все модеры это твердили.И уже за собой тоже заметил — постоянно пишу std:: вместо namespace



0



Эксперт JavaЭксперт С++

8381 / 3613 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

30.10.2012, 23:20

17

Цитата
Сообщение от ZaMaZaN4iK
Посмотреть сообщение

M128K145, в ходе обучения использование using namespace std; вместо std:: способствует, как мне кажется, лучшему восприятию кода.И на ранних этапах обучения программированию использвание пространства предпочтительнее.

если постоянно привыкать спать на потолке(ну как начинающий), то со временем вы уже с трудом сможете переучится спать как и все люди — на диване, который стоит на полу и то, если захочется



0



0 / 0 / 0

Регистрация: 26.01.2011

Сообщений: 8

31.10.2012, 15:09

18

Вставил не помогло, теперь выдает это

Error C2065: cout: необъявленный идентификатор



0



Мой лучший друг-отладчик!

167 / 167 / 30

Регистрация: 24.06.2012

Сообщений: 662

Записей в блоге: 5

31.10.2012, 15:14

19

Нет в С++ оператора end!!!Есть endl.
Замените end на endl



1



0 / 0 / 0

Регистрация: 26.01.2011

Сообщений: 8

31.10.2012, 15:21

20

Ура, спасибо большое. Вот оказывается где собака была зарыта.



0



  • Ошибка vpn указанный порт уже открыт
  • Ошибка visual studio appcrash
  • Ошибка vpn на телефоне
  • Ошибка vp12 spn 520243 fmi 24
  • Ошибка vorbisfile dll для gta san andreas