Меню

Visual studio ошибка c1010

I compile the following code but I get a compile error in Visual Studio that I cannot understand.

#include <iostream>

using namespace std;

int main()
{
    int matchCount, findResult;
    long childPID;
    string userInput = "blank";

    // string to be searched through
    string longString = "The PPSh-41 is a Soviet submachine gun designed by Georgi Shpagin as an inexpensive, simplified alternative to the PPD-40.";

    while (userInput.compare("!wq"));
    {
        // reset variables for reuse
        matchCount = 0;
        findResult = -1;

        cout << "Please enter a word/s to search for (!wq to exit): "; // prompts user for string to search for
        cin >> userInput; // takes user input

        if (userInput.compare("!wq")) // checks user input to see if they still wish to search for a string
        {
            childPID = fork();

            if (childPID == 0)
            {
                while (findResult < longString.length)
                {
                    findResult = longString.find(userInput, findResult + 1, userInput.length);

                    if (findResult < longString.length)
                        matchCount++;
                }

                cout << "There are " << matchCount << " instances of " << userInput << " in longString." << endl;
            }
            else
                cout << "childPID != 0" << endl;
        }
        else
            cout << "User has chosen to exit. Exiting." << endl;
    }

    return 0;
}

The error reads:

«wordcount.cpp(57) : fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include «stdafx.h»‘ to your source?»

I don’t believe I need a header file to run this code. Thank you for all your help in advance.

Glenn Teitelbaum's user avatar

asked Nov 21, 2013 at 5:35

user1800967's user avatar

5

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

Community's user avatar

answered Nov 21, 2013 at 5:47

Glenn Teitelbaum's user avatar

Glenn TeitelbaumGlenn Teitelbaum

9,9483 gold badges35 silver badges79 bronze badges

3

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

answered Nov 21, 2013 at 5:48

asif's user avatar

asifasif

9758 silver badges16 bronze badges

4

Create a new «Empty Project» , Add your Cpp file to the new project, delete the line that includes stdafx.

Done.

The project no longer needs the stdafx. It is added automatically when you create projects with installed templates.
enter image description here

answered Apr 22, 2014 at 2:26

Zahid Rouf's user avatar

Zahid RoufZahid Rouf

1,5612 gold badges11 silver badges10 bronze badges

1

Put this at every source file of your project at the top

#include <stdafx.h>

or / and

Your .cpp file is probably not in the same directory as pch.h

answered Aug 13, 2021 at 23:08

deanqx's user avatar

deanqxdeanqx

111 silver badge4 bronze badges

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Fatal Error C1010

Fatal Error C1010

09/03/2019

C1010

C1010

dfd035f1-a7a2-40bc-bc92-dc4d7f456767

unexpected end of file while looking for precompiled header. Did you forget to add ‘#include name‘ to your source?

Remarks

An include file specified by /Yu isn’t listed in the source file. This option is enabled by default in many Visual Studio C++ project types. The default include file specified by this option is pch.h, or stdafx.h in Visual Studio 2017 and earlier.

In the Visual Studio environment, use one of the following methods to resolve this error:

  • Make sure you haven’t inadvertently deleted, renamed, or removed the pch.h header file or pch.cpp source file from the current project. (In older projects, these files may be named stdafx.h and stdafx.cpp.)

  • Make sure the pch.h or stdafx.h header file is included before any other code or preprocessor directives in your source files. (In Visual Studio, this header file is specified by the Precompiled Header File project property.)

  • You can turn off precompiled header use. If you turn off precompiled headers, it may severely impact build performance.

To turn off precompiled headers

To turn off precompiled header use in a project, follow these steps:

  1. In the Solution Explorer window, right-click the project name, and then choose Properties to open the project Property Pages dialog.

  2. In the Configuration drop-down, select All Configurations.

  3. Select the Configuration properties > C/C++ > Precompiled Headers property page.

  4. In the property list, select the drop-down for the Precompiled Header property, and then choose Not Using Precompiled Headers. Choose OK to save your changes.

  5. In the Solution Explorer window, right-click the pch.cpp source file in your project. (In older projects, the file may be named stdafx.cpp.) Choose Exclude from Project to remove it from the build.

  6. Use the Build > Clean solution menu command for each configuration you build, to delete any project_name.pch files in your intermediate build directories.

See also

Precompiled header files
/Yc (Create precompiled header file)
/Yu (Use precompiled header file)

RRS feed

  • Remove From My Forums
  • Question

  • fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include «stdafx.h»‘ to your source?

    I am using Visual Studio 2005 Academic Edition.

    I clicked «Tool»=>Options=>Debugging=>Edit and Continue.

    Let «Allow precomping» unchecked then.

    Why does this error occury?

    Thanks! 

Answers

  • «Did you forget to add #include «stdafx.h» to your source»?

All replies

  • «Did you forget to add #include «stdafx.h» to your source»?

  • I have generated source code and was trying to compile in release mode (instead of debug).  I got this error.  Putting in the #include «stdafx.h» does not fix the problem.  Anyone know what is going on and why I am getting this error in Release mode and not in Debug mode?

  • I figured out what the problem was.  The entire project needed to be marked as ‘Not Using Precompiled Headers’ in the property pages.  This is under the ‘Configuration Properties’->C/C++->’Precompiled Headers’.  You could just single out the one file if you wanted to also.

    I then was getting some linker unresolved external errors after doing that.  Make sure you also check for any libraries that need to be linked against.  I had (NOINHERIT) in my Additional Dependencies field of the properties.  That field is under the ‘Configuration Properties’->Linker->Input.

    Just wanted to put on the board what I found in case anyone else has these easy setup issues.  These things are different from what I am used to or at least in different places.

    • Proposed as answer by

      Friday, October 7, 2011 7:40 PM

  • Where is

    ‘Configuration Properties’?

    Thanks

    • Proposed as answer by
      Prizzy29
      Monday, October 26, 2009 7:27 AM

  •  The Steve340 wrote:

    I have generated source code and was trying to compile in release mode (instead of debug).  I got this error.  Putting in the #include «stdafx.h» does not fix the problem.  Anyone know what is going on and why I am getting this error in Release mode and not in Debug mode?


  • Once the C++ is open in a project = Tools/options/”edit/countine” you click on the left side / and then close to the bottom is the option to add or remove ‘Precompiled Headers’

    I had an issue, where there ‘Precompiled Headers’ came out of no where, I didn’t even chose it but, I googled the issue and came up with the site. An I read the idea’s on here an searched for it in C++ search and it told me how to do. An I thought I would share the little info.

    • Proposed as answer by
      SANJAY KHACHANE
      Wednesday, June 6, 2012 10:58 AM
    • Unproposed as answer by
      SANJAY KHACHANE
      Wednesday, June 6, 2012 10:59 AM
    • Proposed as answer by
      SANJAY KHACHANE
      Wednesday, June 6, 2012 10:59 AM

  • Go To 

    I am using Visual Studio 2010.

    Clicked New Project —> Visual C++ —> Win32 Console Application —>

    Enter Name Of Application—> Click Ok

    Show «Win32 Application Wizard» — > Click Next —>

    In Scrine Show 

    Additional options: 

    Empty project 
    Export symbols 
    Precompiled header 

    Untick Precompiled Header

    then Finished It

    • Edited by
      SANJAY KHACHANE
      Wednesday, June 6, 2012 11:08 AM

  • Hi..ardmore,

    I was having same problem, but solved it by following manner..

    Open property of that particular page and  go to confi. Property -> c/c++ -> precompiled headers -> set this value to “Not using precompiled Headers”

    • Edited by
      Mayur.Dabhi
      Thursday, September 20, 2012 11:06 AM

  • Thank you soo much.. its works fine steve


Содержание

  1. Fatal Error C1010
  2. Remarks
  3. To turn off precompiled headers
  4. Name already in use
  5. cpp-docs / docs / error-messages / compiler-errors-1 / fatal-error-c1010.md
  6. Неустранимая ошибка C1010
  7. Комментарии
  8. Отключение предкомпилированных заголовков
  9. Visual studio fatal error c1010
  10. Answered by:
  11. Question
  12. Answers
  13. All replies
  14. Visual studio fatal error c1010
  15. Answered by:
  16. Question
  17. Answers
  18. All replies

Fatal Error C1010

unexpected end of file while looking for precompiled header. Did you forget to add ‘#include name‘ to your source?

An include file specified by /Yu isn’t listed in the source file. This option is enabled by default in many Visual Studio C++ project types. The default include file specified by this option is pch.h, or stdafx.h in Visual Studio 2017 and earlier.

In the Visual Studio environment, use one of the following methods to resolve this error:

Make sure you haven’t inadvertently deleted, renamed, or removed the pch.h header file or pch.cpp source file from the current project. (In older projects, these files may be named stdafx.h and stdafx.cpp.)

Make sure the pch.h or stdafx.h header file is included before any other code or preprocessor directives in your source files. (In Visual Studio, this header file is specified by the Precompiled Header File project property.)

You can turn off precompiled header use. If you turn off precompiled headers, it may severely impact build performance.

To turn off precompiled header use in a project, follow these steps:

In the Solution Explorer window, right-click the project name, and then choose Properties to open the project Property Pages dialog.

In the Configuration drop-down, select All Configurations.

Select the Configuration properties > C/C++ > Precompiled Headers property page.

In the property list, select the drop-down for the Precompiled Header property, and then choose Not Using Precompiled Headers. Choose OK to save your changes.

Источник

Name already in use

cpp-docs / docs / error-messages / compiler-errors-1 / fatal-error-c1010.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Fatal Error C1010

unexpected end of file while looking for precompiled header. Did you forget to add ‘#include name‘ to your source?

An include file specified by /Yu isn’t listed in the source file. This option is enabled by default in many Visual Studio C++ project types. The default include file specified by this option is pch.h, or stdafx.h in Visual Studio 2017 and earlier.

In the Visual Studio environment, use one of the following methods to resolve this error:

Make sure you haven’t inadvertently deleted, renamed, or removed the pch.h header file or pch.cpp source file from the current project. (In older projects, these files may be named stdafx.h and stdafx.cpp.)

Make sure the pch.h or stdafx.h header file is included before any other code or preprocessor directives in your source files. (In Visual Studio, this header file is specified by the Precompiled Header File project property.)

You can turn off precompiled header use. If you turn off precompiled headers, it may severely impact build performance.

To turn off precompiled headers

To turn off precompiled header use in a project, follow these steps:

In the Solution Explorer window, right-click the project name, and then choose Properties to open the project Property Pages dialog.

In the Configuration drop-down, select All Configurations.

Select the Configuration properties > C/C++ > Precompiled Headers property page.

In the property list, select the drop-down for the Precompiled Header property, and then choose Not Using Precompiled Headers. Choose OK to save your changes.

Источник

Неустранимая ошибка C1010

непредвиденный конец файла при поиске предкомпилированного заголовка. Вы забыли добавить имя #include в источник?

Комментарии

Включаемый файл, указанный параметром /Yu , не указан в исходном файле. Этот параметр включен по умолчанию во многих типах проектов Visual Studio C++. Файл включения по умолчанию, заданный этим параметром, — pch.h или stdafx.h в Visual Studio 2017 и более ранних версиях.

В среде Visual Studio используйте один из следующих методов для устранения этой ошибки:

Убедитесь, что вы не случайно удалили, не переименовали или не удалили файл заголовка pch.h или исходный файл pch.cpp из текущего проекта. (В более старых проектах эти файлы могут называться stdafx.h и stdafx.cpp.)

Убедитесь, что файл заголовка pch.h или stdafx.h включен перед любым другим кодом или директивами препроцессора в исходных файлах. (В Visual Studio этот файл заголовка задается свойством проекта предварительно скомпилированного файла заголовка .)

Вы можете отключить использование предкомпилированного заголовка. Отключение предкомпилированных заголовков может серьезно повлиять на производительность сборки.

Отключение предкомпилированных заголовков

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

В окне Обозреватель решений щелкните правой кнопкой мыши имя проекта и выберите пункт Свойства, чтобы открыть диалоговое окно Страницы свойств проекта.

В раскрывающемся списке Конфигурация выберите Все конфигурации.

Выберите страницу свойств Свойства> конфигурацииC/C++>Предкомпилированные заголовки.

В списке свойств выберите раскрывающийся список для свойства Precompiled Header (Предкомпилированные заголовки ), а затем выберите Не использовать предкомпилированные заголовки. Выберите ОК для сохранения внесенных изменений.

Источник

Visual studio fatal error c1010

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

i included an vb dll into vc++. When i compiled i am getting this error.

fatal error C1010: unexpected end of file while looking for precompiled header directive in the .c file produced from the idl file.

i included comdef.h and header file produced by midl compiler to the source file. i had the dll file in the same directory of vc++ project folder. Any thing need to be set here ?

Answers

Produced from the idl file? Thats not possible.

You defined your project to use precompiled header files. So your c file or cpp files must include the file that is defined for precompilation at the top of it.

Usually #include «stdafx.h» must be placed into your cpp file.

If you want to include the c file created form the idl. You can either include it into obne of your files, or you remove the options to use precompiled headers for this specific source file.

Thank you Mr. Martin,

Now i got after setting the precompiled headers off.

It is in Project-> Settings->C/C++->Category->Precompiled headers->not using precompiled headers. Thanks once again.

Produced from the idl file? Thats not possible.

You defined your project to use precompiled header files. So your c file or cpp files must include the file that is defined for precompilation at the top of it.

Usually #include «stdafx.h» must be placed into your cpp file.

If you want to include the c file created form the idl. You can either include it into obne of your files, or you remove the options to use precompiled headers for this specific source file.

Thank you Mr. Martin,

Now i got after setting the precompiled headers off.

It is in Project-> Settings->C/C++->Category->Precompiled headers->not using precompiled headers. Thanks once again.

Hi, I’m a beginer to VC++. I wrote the following code. When compils it it shows «fatal error C1010: unexpected end of file while looking for precompiled header directive». when I included the stdafx.h it shows 3 erros where as 1 before. I tried all the headerfile setting under project->settings->c/c++,but it doesnot work. I’m using visual studio 6.0. Sir please help me.
Thanks in advance.

int_stdcall WinMain(
HINSTANCE hInstancs,
HINSTANCE hPrevInstance,
LPSTR lpszCmdLine,
int nCmdShow)
<
MessageBox(0,»Hello»,»Hello»,0);
return(0);
>

Источник

Visual studio fatal error c1010

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

i included an vb dll into vc++. When i compiled i am getting this error.

fatal error C1010: unexpected end of file while looking for precompiled header directive in the .c file produced from the idl file.

i included comdef.h and header file produced by midl compiler to the source file. i had the dll file in the same directory of vc++ project folder. Any thing need to be set here ?

Answers

Produced from the idl file? Thats not possible.

You defined your project to use precompiled header files. So your c file or cpp files must include the file that is defined for precompilation at the top of it.

Usually #include «stdafx.h» must be placed into your cpp file.

If you want to include the c file created form the idl. You can either include it into obne of your files, or you remove the options to use precompiled headers for this specific source file.

Thank you Mr. Martin,

Now i got after setting the precompiled headers off.

It is in Project-> Settings->C/C++->Category->Precompiled headers->not using precompiled headers. Thanks once again.

Produced from the idl file? Thats not possible.

You defined your project to use precompiled header files. So your c file or cpp files must include the file that is defined for precompilation at the top of it.

Usually #include «stdafx.h» must be placed into your cpp file.

If you want to include the c file created form the idl. You can either include it into obne of your files, or you remove the options to use precompiled headers for this specific source file.

Thank you Mr. Martin,

Now i got after setting the precompiled headers off.

It is in Project-> Settings->C/C++->Category->Precompiled headers->not using precompiled headers. Thanks once again.

Hi, I’m a beginer to VC++. I wrote the following code. When compils it it shows «fatal error C1010: unexpected end of file while looking for precompiled header directive». when I included the stdafx.h it shows 3 erros where as 1 before. I tried all the headerfile setting under project->settings->c/c++,but it doesnot work. I’m using visual studio 6.0. Sir please help me.
Thanks in advance.

int_stdcall WinMain(
HINSTANCE hInstancs,
HINSTANCE hPrevInstance,
LPSTR lpszCmdLine,
int nCmdShow)
<
MessageBox(0,»Hello»,»Hello»,0);
return(0);
>

Источник

Speed up your PC in just a few clicks

  • 1. Download and install ASR Pro
  • 2. Open the application and click on the Scan button
  • 3. Select the files or folders you want to restore and click on the Restore button
  • Download this software now and say goodbye to your computer problems.

    Sometimes your computer may give you a c1010 Visual Studio error message. There can be many reasons for this problem. When someone creates a new project that exists in Visual Studio, they manually create a precompiled header file called pch. added to the project. pre-compiled h2 tags are only compiled if they, and even the files they contain, are new. If you only make changes to the project’s source code, your amplification skips compilation, which usually uses a precompiled header.

    How do I get rid of PCH h in Visual Studio?

    Open your projectThen select “Project” “Application Name > Properties…”. Expand Configuration Properties > > c/c++ Precompiled Headers. Set the Precompiled Header option to Do not use precompiled headers.

    When I compile the following code, I get a compilation error in Visual Studio that I don’t understand.

    #include by standard with namespace;interior()    match interval, find result;   long ChildPID;    field userInput = "empty";    // search string    longString sequence = "PPSh-41 is a Soviet submachine gun designed by Georgy Shpagin as a natural, simplified and cheap PPD-40." ;   anyway (userInput.compare("!wq"));            // Reset variables to reuse them        number of matches = 0;        the search result is -1;        cout << "Please enter one or more search words To (!wq Exit): "; // ask the person to find the string        cin >> user input; // Accept input from male or female        if (userInput.compare("!wq")) // The bank checks the user input to see if there are manyDoes anyone else want to search for the real string                    childPID = fork();           While (childPID == 0)                            and (findResult < longString.length)                                    = findResult longString.find(userInput, findResult + UserInput 1,.length);                    in the case where (findResult < longString.length)                        number of matches++;                                cout << "Definitely there will be " << matchCount << ' instances of " << userInput << in longString." << end;                        different                cout << "childPID ! means 0" << endl;                different            cout << "The user has chosen to exit the program. Quit.<< " endl;     Returns 0;

    error c1010 visual studio

    «wordcount.cpp(57): Fatal error Shocking c1010: Looking for precompiled header at end of file. Forgot to include ‘#include «stdafx.h»‘ in source code?

    Did you forget to add Stdafx H to your source?

    Did you forget to include ‘#include «stdafx»? in your source? The fact that you are getting this type of error means that you are sure about this «Win32 Application Helper» (Visual Studio 2015) or possibly the «Windows Desktop Helper» (Visual Studio 2017).

    I don’t think I need an h2 tag file to run this code. Thanks in advance for your efforts.

    Read More:

    Fatal error C1010: Unexpected end of file found while searching for precompiled headers. Did you «#include», forgot to add stdafx.h to the code?
    Source Error Parsing:
    The above error occurs because compilers mostly look for prefixes.But the compiled sensor header (#include «stdafx.If h default»), the file definitely does not complete properly. Header file «stdafx.h» found in precompiled non-instructions.
    project (because the specific CPP point file uses a precompiled header (/YU) by default, add third-party documents that # contain precompiled «stdafx.h» directives, for this reason the compiler in the CPP file is not found at all until the end)
    My problem when it came up was adding files containing large un tuo des to MFC. Hand. RPC folder. These .h and .cpp computer data files belong to the standard category of Adaptive C++ source code and have a closer relationship to MFC.
    Resolution: A.

    error c1010 visual studio

    1) Solution Explorer, available by right-clicking on the corresponding one. CPP file, «Properties» visitor
    2) on the retrieved page in the configuration properties check PM «C/C++», to «Precompiled Header»
    3) change to the right of the first line of the option «create/use precompiled title» changed from previously «use comsawed header (/w)» to «do not use precompiled header» 4)
    Note: second
    .
    (not recommended)
    About 1) solution, right-click on the project itself, select «Properties»
    2) Go back to C/c++ configuration properties -> -> Change «Use precompiled (/YU)» headers should not apply «very precompiled header»

    Download this software now and say goodbye to your computer problems.

    Oshibka C1010 Vizualnaya Studiya
    Erreur C1010 Studio Visuel
    Error C1010 Estudio Visual
    Fel C1010 Visual Studio
    Fout C1010 Visuele Studio
    Erro C1010 Visual Studio
    Blad C1010 Studio Wizualne
    Errore C1010 Visual Studio
    Fehler C1010 Visual Studio
    오류 C1010 비주얼 스튜디오

    Harrison Crist

    HerMak

    1 / 0 / 1

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

    Сообщений: 35

    1

    05.03.2018, 16:45. Показов 9022. Ответов 5

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


    Решил попробовать сделать змейку на чистом с++, но тут какая то ошибка, игру разрабатываю в Visual studio 2017 код ошибки С1010
    непредвиденный конец файла во время поиска предкомпилированного заголовка. Возможно, вы забыли добавить директиву «#include «stdafx.h»»
    Добавлял данную библиотеку-не помогло.

    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
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    
    #include <iostream>
    using namespace std;
    const int width = 20;
    const int height = 20;
    int x, y;
    int fruitx, fruity, score;
    bool GameOver;
    enum eDirection { STOP = 0, LEFT, RIHGT, UP, DOWN };
    eDirection dir;
     
    void SetUp()
    {
        GameOver = false;
        dir = STOP;
        x = width / 2;
        y = height / 2;
        fruitx = rand() % width;
        fruity = rand() % height;
        score = 0;
    }
    void Draw()
    {
        system("cls");
        for (int i = 0; i<width; i++)cout << "#";
        cout << endl;
     
        for (int i = 0; i<height; i++)
        {
            for (int j = 0; j<width; i++)
            {
                if (j == 0 || j == width - 1)
                    cout << "#";
                cout << " ";
            }
            cout << endl;
        }
     
        for (int i = 0; i<width ; i++) cout << "#";
        cout << endl;
    }
    void Input()
    {
     
    }
    void Logic()
    {
     
    }
    int main(int argc, char** argv) {
        SetUp();
        while (!GameOver)
        {
            Draw();
            Input();
            Logic();
        }
        return 0;
    }

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    3433 / 2812 / 1249

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

    Сообщений: 9,426

    05.03.2018, 16:46

    2

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

    Добавлял данную библиотеку-не помогло.

    Куда добавлял? Как добавлял? В коде ничего такого не наблюдаю. И это не библиотека.



    0



    1 / 0 / 1

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

    Сообщений: 35

    05.03.2018, 16:50

     [ТС]

    3

    Не библиотеку, извиняюсь, а вот такой строчкой
    #include «stdafx.h



    0



    3433 / 2812 / 1249

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

    Сообщений: 9,426

    05.03.2018, 16:52

    4

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

    а вот такой строчкой
    #include «stdafx.h

    Код со строчкой покажи.



    0



    HerMak

    1 / 0 / 1

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

    Сообщений: 35

    05.03.2018, 16:52

     [ТС]

    5

    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
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    
    #include <iostream>
    #include "stdafx.h"
    using namespace std;
    const int width = 20;
    const int height = 20;
    int x, y;
    int fruitx, fruity, score;
    bool GameOver;
    enum eDirection { STOP = 0, LEFT, RIHGT, UP, DOWN };
    eDirection dir;
     
    void SetUp()
    {
        GameOver = false;
        dir = STOP;
        x = width / 2;
        y = height / 2;
        fruitx = rand() % width;
        fruity = rand() % height;
        score = 0;
    }
    void Draw()
    {
        system("cls");
        for (int i = 0; i<width; i++)cout << "#";
        cout << endl;
     
        for (int i = 0; i<height; i++)
        {
            for (int j = 0; j<width; i++)
            {
                if (j == 0 || j == width - 1)
                    cout << "#";
                cout << " ";
            }
            cout << endl;
        }
     
        for (int i = 0; i<width ; i++) cout << "#";
        cout << endl;
    }
    void Input()
    {
     
    }
    void Logic()
    {
     
    }
    int main(int argc, char** argv) {
        SetUp();
        while (!GameOver)
        {
            Draw();
            Input();
            Logic();
        }
        return 0;
    }



    0



    nd2

    3433 / 2812 / 1249

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

    Сообщений: 9,426

    05.03.2018, 16:55

    6

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

    Решение

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

    C++
    1
    
    #include "stdafx.h"

    Это выше всех инклудов должно быть.



    1



    Добавлено 27 марта 2021 в 12:55

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

    Общие проблемы во время выполнения

    Вопрос: При выполнении программы окно консоли мигает, а затем сразу закрывается.


    Сначала добавьте или убедитесь, что следующие строки находятся в верхней части вашей программы (пользователи Visual Studio должны убедиться, что эти строки появляются после #include "pch.h" или #include "stdafx.h", если таковые существуют):

    #include <iostream>
    #include <limits>

    Во-вторых, добавьте следующий код в конец функции main() (прямо перед оператором return):

    // сбрасываем все флаги ошибок
    std::cin.clear();
    // игнорируем любые символы во входном буфере, пока не найдем новую строку
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    // получаем от пользователя еще один символ
    std::cin.get();

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

    Другие решения, такие как обычно предлагаемое system("pause"), могут работать только в определенных операционных системах, и их следует избегать.

    Более старые версии Visual Studio могут не приостанавливаться, когда программа запускается в режиме Начать с отладкой (Start With Debugging) (F5). Попробуйте запустить в режиме Начать без отладки (Start Without Debugging) (Ctrl + F5).

    Вопрос: Я запустил свою программу, получил окно, но ничего не выводится.


    Выполнение может блокировать ваш антивирус. Попробуйте временно отключить его и посмотрите, не в этом ли проблема.

    Вопрос: Моя программа компилируется, но работает некорректно. Что не так?


    Отладьте ее! Советы по диагностике и отладке программ приведены далее в главе 3.

    Общие проблемы времени компиляции

    Вопрос: Когда я компилирую свою программу, я получаю ошибку о неразрешенном внешнем символе _main или _WinMain@16


    Это означает, что ваш компилятор не может найти вашу функцию main(). А все программы должны включать в себя эту функцию.

    Есть несколько вещей, которые нужно проверить:

    1. Содержит ли ваш код функцию с именем main?
    2. Правильно ли написано имя main?
    3. Когда вы компилируете свою программу, видите ли вы, что файл, содержащий функцию main(), компилируется? Если нет, либо переместите функцию main() в другой файл, либо добавьте этот файл в свой проект (для получения дополнительной информации о том, как это сделать, смотрите урок «2.7 – Программы с несколькими файлами кода»).
    4. Вы точно создали консольный проект? Попробуйте создать новый консольный проект.

    Вопрос: Я пытаюсь использовать функциональность C++11/14/17/XX, но она не работает.


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

    В случае с современными IDE/компиляторами ваш компилятор может по умолчанию использовать более старый стандарт языка. Мы рассмотрим, как изменить стандарт языка в уроке «0.12 – Настройка компилятора: выбор стандарта языка».

    Вопрос: При попытке использовать cin, cout или endl компилятор говорит, что cin, cout или endl являются «необъявленными идентификаторами».


    Во-первых, убедитесь, что вы включили следующую строку в верхней части файла:

    #include <iostream>

    Во-вторых, убедитесь, что каждое использование cin, cout и endl имеет префикс «std::«. Например:

    std::cout << "Hello world!" << std::endl;

    Если это не решит вашу проблему, возможно, ваш компилятор устарел или установка повреждена. Попробуйте переустановить и/или обновить компилятор до последней версии.

    Вопрос: При попытке использовать endl для завершения напечатанной строки компилятор говорит, что end1 является «необъявленным идентификатором».


    Убедитесь, что вы не перепутали букву l (нижний регистр L) в endl с цифрой 1. endl – это все буквы. Убедитесь, что ваш редактор использует шрифт, который проясняет разницу между строчной буквой L, заглавной i и цифрой 1. Кроме того, во многих шрифтах, не предназначенных для программирования, можно легко перепутать заглавную букву o и цифру ноль.

    Проблемы с Visual Studio

    Вопрос: При компиляции с помощью Microsoft Visual C++ вы получаете фатальную ошибку C1010 с сообщением типа «c:vcprojectstest.cpp(263) :fatal error C1010: unexpected end of file while looking for precompiled header directive» (неожиданный конец файла при поиске директивы предварительно скомпилированного заголовка).


    Эта ошибка возникает, когда компилятор Microsoft Visual C++ настроен на использование предварительно скомпилированных заголовков, но один (или несколько) ваших файлов кода C++ не включает #include "stdafx.h" или #include "pch.h" в качестве первой строки кода файла.

    Предлагаемое нами решение – отключить предварительно скомпилированные заголовки, как это сделано в уроке «0.7 – Компиляция вашей первой программы».

    Если вы хотите, чтобы предварительно скомпилированные заголовки были включены, чтобы решить эту проблему, просто найдите файл(ы), вызывающий ошибку (в приведенной выше ошибке виновником является test.cpp), и добавьте следующую строку в самом верху файла):

    #include "pch.h"

    В более старых версиях Visual Studio используется stdafx.h вместо pch.h, поэтому, если pch.h не решает проблему, попробуйте stdafx.h.

    Обратите внимание, что для программ с несколькими файлами каждый файл кода C++ должен начинаться с этой строки.

    Кроме того, вы можете отключить предварительно скомпилированные заголовки.

    Вопрос: Visual Studio выдает следующую ошибку: «1MSVCRTD.lib(exe_winmain.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function «int __cdecl invoke_main(void)» (?invoke_main@@YAHXZ)» (неразрешенный внешний символ _WinMain@16).


    Скорее всего, вы создали не консольное приложение, а графическое приложение Windows. Создайте заново свой проект и убедитесь, что вы создали его как консольный проект Windows (или Win32).

    Вопрос: Когда я компилирую свою программу, я получаю предупреждение «Cannot find or open the PDB file» (не могу найти или открыть файл PDB).


    Это предупреждение, а не ошибка, поэтому оно не должно повлиять на вашу программу. Однако она раздражает. Чтобы исправить это, перейдите в меню Debug (Отладка) → Options and Settings (Параметры) → Symbols (Символы) и установите флажок Microsoft Symbol Server (Сервер символов Microsoft).

    Прочее

    Вопрос: У меня есть еще одна проблема, которую я не могу понять. Как я могу быстро получить ответ?


    По мере обучения у вас, несомненно, будут возникать вопросы или неожиданные проблемы. Что делать дальше, зависит от вашей проблемы. Но в целом есть несколько вещей, которые вы можете попробовать.

    Сначала спросите Google. Найдите хороший способ сформулировать свой вопрос и выполните поиск в Google. Если вы получили сообщение об ошибке, вставьте точное сообщение в Google, используя кавычки. Скорее всего, кто-то уже задавал тот же вопрос, и вы найдете ответ.

    Если это не поможет, спросите на сайте вопросов и ответов. Существуют веб-сайты, предназначенные для вопросов и ответов о программировании, например, Stack Overflow. Попробуйте разместить там свой вопрос. Не забудьте подробно описать, в чем заключается ваша проблема, и включить всю необходимую информацию, например, какую ОС и какую IDE вы используете.

    Теги

    C++ / CppFAQLearnCppДля начинающихОбучениеПрограммирование

    • Remove From My Forums
    • Question

    • Hi everyone,

      I am new member to this group..I am trying to build a VC++ project which has 2 source files (a.cpp, b.cpp) , in which one  a.cpp source file is written by somebody and I have to use it for my project and cannot change nor include in it any header files..when I am building my original source file i.e b.cpp of my project, its giving me the error

      C1010: UNEXPECTED END OF FILE WHILE LOOKING FOR PRECOMPILED HEADER FILE : DID U INCLUDE ‘ #INCLUDE «STDAFX.H»‘ TO YOUR SOURCE.. —a.cpp

      I have gone through a.cpp and stdafx.h is not included whoever has written it .. But I have set the project properties to use precompiled header file option (b.pch)..I have seen the properties of a.cpp file and the precompiled header file is included..Still I get the error.

      Could anyone please help me in this regard..I am little bit new to vc++ and I am njot sure if I need to change any settings..To my knowledge I have in cluded all the header files..Thanks in advance.

    Answers

    • It seems you have created a project with using precompileed headers and then add existing a.cpp into you project which has no #include «stdafx.h». Try following steps:

      1. Add #include «stdafx.h» to the very beginning(before every other including) of a.cpp, If you don’t want to change or modify a.cpp, then use step 2.

      2.Try not use precompiled headers in your project, set the Create/Use Precompiled Header property of source files to Not Using Precompiled Headers.

    • It is hard to have a consistent way to solve such issue, the key is to understand the reason behind this Link Error by searching on MSDN Library, and do the troubleshooting base on the knowledge you have just learned. For LNK2019, which happens frequently, you can refer to Link Tools Error LNK2019 which will be helpful when you have them next time.

      best regards,

      rico

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Visual studio ошибка 1168
  • Visual studio окно ошибок как открыть