Ошибка c2065 string необъявленный идентификатор

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.

GlebCom

0 / 0 / 0

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

Сообщений: 15

1

24.08.2018, 03:40. Показов 3057. Ответов 2

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


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

Здравствуйте!!!

У меня такая проблема. Я создал header file и соответствующий ему исходный файл.
При #include этого header file в main появляются ошибки
1) C2065 string: необъявленный идентификатор
2) C2146 синтаксическая ошибка: отсутствие «)» перед идентификатором «str»
3) C3861 IsPalindrom: идентификатор не найден

Непонятно, почему)))))) мне кажется все правильно))))

файл с main

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include "Week_2.h"
using namespace std;
 
int main() {
    
    string str1;
    cin >> str1;
 
 
    cout << IsPalindrom(str1) << endl;
 
    system("pause");
    return 0;
}

заголовочный файл

C++
1
2
3
4
5
6
#ifndef WEEK_2_H
#define WEEK_2_H
 
bool IsPalindrom(string str);
 
#endif

и файл с функцией

C++
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>
 
using namespace std;
 
 
bool IsPalindrom(string str) {
    /* code */
}

Спасибо!!!



0



zss

Модератор

Эксперт С++

13320 / 10454 / 6253

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

Сообщений: 27,910

24.08.2018, 06:00

2

Лучший ответ Сообщение было отмечено GlebCom как решение

Решение

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

using namespace std;

поставьте перед

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

#include «Week_2.h»

Или в Week_2.h напишите

C++
1
bool IsPalindrom(std::string str);



1



0 / 0 / 0

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

Сообщений: 15

24.08.2018, 10:32

 [ТС]

3

zss, Спасибо!)))))



0



description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2065

Compiler Error C2065

06/29/2022

C2065

C2065

78093376-acb7-45f5-9323-5ed7e0aab1dc

Compiler Error C2065

identifier‘ : undeclared identifier

The compiler can’t find the declaration for an identifier. There are many possible causes for this error. The most common causes of C2065 are that the identifier hasn’t been declared, the identifier is misspelled, the header where the identifier is declared isn’t included in the file, or the identifier is missing a scope qualifier, for example, cout instead of std::cout. For more information on declarations in C++, see Declarations and Definitions (C++).

Here are some common issues and solutions in greater detail.

The identifier is undeclared

If the identifier is a variable or a function name, you must declare it before it can be used. A function declaration must also include the types of its parameters before the function can be used. If the variable is declared using auto, the compiler must be able to infer the type from its initializer.

If the identifier is a member of a class or struct, or declared in a namespace, it must be qualified by the class or struct name, or the namespace name, when used outside the struct, class, or namespace scope. Alternatively, the namespace must be brought into scope by a using directive such as using namespace std;, or the member name must be brought into scope by a using declaration, such as using std::string;. Otherwise, the unqualified name is considered to be an undeclared identifier in the current scope.

If the identifier is the tag for a user-defined type, for example, a class or struct, the type of the tag must be declared before it can be used. For example, the declaration struct SomeStruct { /*...*/ }; must exist before you can declare a variable SomeStruct myStruct; in your code.

If the identifier is a type alias, the type must be declared by a using declaration or typedef before it can be used. For example, you must declare using my_flags = std::ios_base::fmtflags; before you can use my_flags as a type alias for std::ios_base::fmtflags.

Example: misspelled identifier

This error commonly occurs when the identifier name is misspelled, or the identifier uses the wrong uppercase and lowercase letters. The name in the declaration must exactly match the name you use.

// C2065_spell.cpp
// compile with: cl /EHsc C2065_spell.cpp
#include <iostream>
using namespace std;
int main() {
    int someIdentifier = 42;
    cout << "Some Identifier: " << SomeIdentifier << endl;
    // C2065: 'SomeIdentifier': undeclared identifier
    // To fix, correct the spelling:
    // cout << "Some Identifier: " << someIdentifier << endl;
}

Example: use an unscoped identifier

This error can occur if your identifier isn’t properly scoped. If you see C2065 when you use cout, a scope issue is the cause. When C++ Standard Library functions and operators aren’t fully qualified by namespace, or you haven’t brought the std namespace into the current scope by using a using directive, the compiler can’t find them. To fix this issue, you must either fully qualify the identifier names, or specify the namespace with the using directive.

This example fails to compile because cout and endl are defined in the std namespace:

// C2065_scope.cpp
// compile with: cl /EHsc C2065_scope.cpp
#include <iostream>
// using namespace std;   // Uncomment this line to fix

int main() {
    cout << "Hello" << endl;   // C2065 'cout': undeclared identifier
                               // C2065 'endl': undeclared identifier
    // Or try the following line instead
    std::cout << "Hello" << std::endl;
}

Identifiers that are declared inside of class, struct, or enum class types must also be qualified by the name of their enclosing scope when you use them outside of that scope.

Example: precompiled header isn’t first

This error can occur if you put any preprocessor directives, such as #include, #define, or #pragma, before the #include of a precompiled header file. If your source file uses a precompiled header file (that is, if it’s compiled by using the /Yu compiler option) then all preprocessor directives before the precompiled header file are ignored.

This example fails to compile because cout and endl are defined in the <iostream> header, which is ignored because it’s included before the precompiled header file. To build this example, create all three files, then compile pch.h (some versions of Visual Studio use stdafx.cpp), then compile C2065_pch.cpp.

// pch.h (stdafx.h in Visual Studio 2017 and earlier)
#include <stdio.h>

The pch.h or stdafx.h source file:

// pch.cpp (stdafx.cpp in Visual Studio 2017 and earlier)
// Compile by using: cl /EHsc /W4 /c /Ycstdafx.h stdafx.cpp
#include "pch.h"

Source file C2065_pch.cpp:

// C2065_pch.cpp
// compile with: cl /EHsc /W4 /Yustdafx.h C2065_pch.cpp
#include <iostream>
#include "stdafx.h"
using namespace std;

int main() {
    cout << "Hello" << endl;   // C2065 'cout': undeclared identifier
                               // C2065 'endl': undeclared identifier
}

To fix this issue, add the #include of <iostream> into the precompiled header file, or move it after the precompiled header file is included in your source file.

Example: missing header file

The error can occur if you haven’t included the header file that declares the identifier. Make sure the file that contains the declaration for the identifier is included in every source file that uses it.

// C2065_header.cpp
// compile with: cl /EHsc C2065_header.cpp

//#include <stdio.h>
int main() {
    fpos_t file_position = 42; // C2065: 'fpos_t': undeclared identifier
    // To fix, uncomment the #include <stdio.h> line
    // to include the header where fpos_t is defined
}

Another possible cause is if you use an initializer list without including the <initializer_list> header.

// C2065_initializer.cpp
// compile with: cl /EHsc C2065_initializer.cpp

// #include <initializer_list>
int main() {
    for (auto strList : {"hello", "world"})
        if (strList == "hello") // C2065: 'strList': undeclared identifier
            return 1;
    // To fix, uncomment the #include <initializer_list> line
}

You may see this error in Windows Desktop app source files if you define VC_EXTRALEAN, WIN32_LEAN_AND_MEAN, or WIN32_EXTRA_LEAN. These preprocessor macros exclude some header files from windows.h and afxv_w32.h to speed compiles. Look in windows.h and afxv_w32.h for an up-to-date description of what’s excluded.

Example: missing closing quote

This error can occur if you’re missing a closing quote after a string constant. It’s an easy way to confuse the compiler. The missing closing quote may be several lines before the reported error location.

// C2065_quote.cpp
// compile with: cl /EHsc C2065_quote.cpp
#include <iostream>

int main() {
    // Fix this issue by adding the closing quote to "Aaaa"
    char * first = "Aaaa, * last = "Zeee";
    std::cout << "Name: " << first
        << " " << last << std::endl; // C2065: 'last': undeclared identifier
}

Example: use iterator outside for loop scope

This error can occur if you declare an iterator variable in a for loop, and then you try to use that iterator variable outside the scope of the for loop. The compiler enables the /Zc:forScope compiler option by default. For more information, see Debug iterator support.

// C2065_iter.cpp
// compile with: cl /EHsc C2065_iter.cpp
#include <iostream>
#include <string>

int main() {
    // char last = '!';
    std::string letters{ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" };
    for (const char& c : letters) {
        if ('Q' == c) {
            std::cout << "Found Q!" << std::endl;
        }
        // last = c;
    }
    std::cout << "Last letter was " << c << std::endl; // C2065
    // Fix by using a variable declared in an outer scope.
    // Uncomment the lines that declare and use 'last' for an example.
    // std::cout << "Last letter was " << last << std::endl; // C2065
}

Example: preprocessor removed declaration

This error can occur if you refer to a function or variable that is in conditionally compiled code that isn’t compiled for your current configuration. The error can also occur if you call a function in a header file that currently isn’t supported in your build environment. If certain variables or functions are only available when a particular preprocessor macro is defined, make sure the code that calls those functions can only be compiled when the same preprocessor macro is defined. This issue is easy to spot in the IDE: The declaration for the function is greyed out if the required preprocessor macros aren’t defined for the current build configuration.

Here’s an example of code that works when you build in Debug, but not Release:

// C2065_defined.cpp
// Compile with: cl /EHsc /W4 /MT C2065_defined.cpp
#include <iostream>
#include <crtdbg.h>
#ifdef _DEBUG
    _CrtMemState oldstate;
#endif
int main() {
    _CrtMemDumpStatistics(&oldstate);
    std::cout << "Total count " << oldstate.lTotalCount; // C2065
    // Fix by guarding references the same way as the declaration:
    // #ifdef _DEBUG
    //    std::cout << "Total count " << oldstate.lTotalCount;
    // #endif
}

Example: C++/CLI type deduction failure

This error can occur when calling a generic function, if the intended type argument can’t be deduced from the parameters used. For more information, see Generic Functions (C++/CLI).

// C2065_b.cpp
// compile with: cl /clr C2065_b.cpp
generic <typename ItemType>
void G(int i) {}

int main() {
   // global generic function call
   G<T>(10);     // C2065
   G<int>(10);   // OK - fix with a specific type argument
}

Example: C++/CLI attribute parameters

This error can also be generated as a result of compiler conformance work that was done for Visual Studio 2005: parameter checking for Visual C++ attributes.

// C2065_attributes.cpp
// compile with: cl /c /clr C2065_attributes.cpp
[module(DLL, name=MyLibrary)];   // C2065
// try the following line instead
// [module(dll, name="MyLibrary")];

[export]
struct MyStruct {
   int i;
};

Была программа (которая считает стоимость всех компьюеров на складе, а также выодит инфу о компьютере с самой высокой тактовой частотой процессора стоимостью от 20 до 30к):

#include <locale>
#include <cstdlib>
#include <cstring>
#include <iostream>

using namespace std;

struct computer
{

    char cpu_brand[10];
    unsigned int cpu_clock;
    char motherboard[10];
    char harddrive[10];
    char videoacrd[10];
    char wifi[10];
    unsigned int price;
    unsigned int store;

    void getInfo()
    {
        cout << " Brand of CPU: " << cpu_brand << endl;
        cout << " CPU clock in Mhz: " << cpu_clock << endl;
        cout << " Brand of motherboard: " << motherboard << endl;
        cout << " Brand of HDD: " << harddrive << endl;
        cout << " Brand of GPU: " << videoacrd << endl;
        cout << " Presence of wi-fi: " << wifi << endl;
        cout << " Cost of computer: " << price << endl;
        cout << " Quantity in stock: " << store << endl;
    }
};

const int N = 3;

computer collection[N]; // создаем массив из N структур computer

int main()
{
    setlocale(LC_ALL, "rus");
    for (int i = 0; i < N; i++)
    {
        printf("nnEnter info abot computer №%dn", i + 1);

        printf(" Brand of CPU - ");
        std::cin.getline(collection[i].cpu_brand, 10);

        printf(" CPU clock in Mhz - ");
        scanf_s("%u", &collection[i].cpu_clock);
        getchar();

        printf(" Brand of motherboard - ");
        std::cin.getline(collection[i].motherboard, 10);

        printf(" Brand of HDD - ");
        std::cin.getline(collection[i].harddrive, 10);

        printf(" Brand of GPU - ");
        std::cin.getline(collection[i].videoacrd, 10);

        printf(" Presence of wi-fi - ");
        std::cin.getline(collection[i].wifi, 10);

        printf(" Cost of computer - ");
        scanf_s("%u", &collection[i].price);
        getchar();

        printf(" Quantity in stock - ");
        scanf_s("%u", &collection[i].store);
        getchar();
    }


    int S;
    int SS = 0;
    for (int i = 0; i < N; i++) {
        S = collection[i].price * collection[i].store;
        SS = SS + S;
    }
    cout << "Cost of all computers in a store " << SS << endl;



    computer buff = collection[0]; // будем хранить объект струтктуры вместо числа
    for (int i = 0; i < N; i++) {
        if (collection[i].price < 30000 || collection[i].price > 20000) {
            if (buff.cpu_clock < collection[i].cpu_clock) {
                buff = collection[i];
            }
        }
    }

    cout << "The computer with the highest processor clock cost from 20 to 30 t.r: " << endl;
    buff.getInfo(); // получаем информацию о компьютере

    system("pause");
    return 0;
}

Потребовалось переделать ее так, чтобы данные считывались из файла, вместо char был string,была реализована динамическая память.
Получилось следующее:

#include <iostream> 
#include <locale> 
#include <string> 
#include <fstream> 

using namespace std;

struct computer
{

    string cpu_brand;
    unsigned int cpu_clock;
    string motherboard;
    string harddrive;
    string videoacrd;
    string wifi;
    unsigned int price;
    unsigned int store;

    void getInfo()
    {
        cout << " Производитель процессора: " << cpu_brand << endl;
        cout << " Частота процессора в МГц: " << cpu_clock << endl;
        cout << " Производитель материнской платы: " << motherboard << endl;
        cout << " Производитель HDD: " << harddrive << endl;
        cout << " Производитель видеокарты: " << videoacrd << endl;
        cout << " Наличие wifi: " << wifi << endl;
        cout << " Стоимость компьютера: " << price << endl;
        cout << " Количество компьютеров на складе: " << store << endl;
    }
};


computer FileRead(ifstream &file)
{
    computer acomputer;
    getline(file, acpu_brand);
    file >> acpu_clock;
    getline(file, amotherboard);
    getline(file, aharddrive);
    getline(file, avideoacrd);
    getline(file, awifi);
    file >> aprice;
    file >> astore;

    return acomputer;
}

void FileInfo(computer acomputer, int i)
{
    cout << "nn Данные для компютера №" << (i + 1) << endl;
    cout << " Производитель процессора - " << acpu_brand << endl;
    cout << " Частота процессора в МГц - " << acpu_clock << endl;
    cout << " Производитель материнской платы - " << amotherboard << endl;
    cout << " Производитель HDD - " << aharddrive << endl;
    cout << " Производитель видеокарты  - " << avideoacrd << endl;
    cout << " Наличие wifi - " << awifi << endl;
    cout << " Стоимость компьютера - " << aprice << endl;
    cout << " Количество компьютеров на складе - " << astore << endl;
}


void CostOf(computer *collection, int N, string aprice, string astore)
{
    for (int i = 0; i < N; i++)
        int S;
    int SS = 0;
    for (int i = 0; i < N; i++) {
        S = collection[i].price * collection[i].store;
        SS = SS + S;
    }
    cout << "Стоимость всех компьютеров на складе " << SS << endl;
}


void MaxClock(computer *collection, int N, string aprice, string acpu_clock)
{
    computer buff = collection[0]; // будем хранить объект струтктуры вместо числа
    for (int i = 0; i < N; i++) {
        if (collection[i].price < 30000 || collection[i].price > 20000) {
            if (buff.cpu_clock < collection[i].cpu_clock) {
                buff = collection[i];
            }
        }
    }

    cout << "Компьютер с самой высокой тактовой частотой процессора стоимостью от 20 до 30 тр: " << endl;
    buff.getInfo(); // получаем информацию о компьютере
}

int main()
{
    setlocale(LC_ALL, "rus");

    ifstream infile;
    infile.open("file.txt");
    int N;
    infile >> N;
    collection = new computer[N];

    for (int i = 0; i < N; i++)
        collection[i] = FlleRead(infile);

    for (int i = 0; i < N, i++)
        FileInfo(collection[i], i)

    CostOf(collection, N);
    MaxClock(collection, N);

    delete[] collection;
    infile.close();
    system("pause");
    return 0;

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

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.

  • Ошибка c2064 результатом вычисления фрагмента не является функция принимающая 1 аргументов
  • Ошибка c2061 синтаксическая ошибка идентификатор tchar
  • Ошибка c2061 синтаксическая ошибка идентификатор string
  • Ошибка c2059 синтаксическая ошибка константа
  • Ошибка c2059 синтаксическая ошибка using namespace