0 / 0 / 1
Регистрация: 26.04.2018
Сообщений: 19
1

Не открывается окно при использовании graphics.h

21.03.2019, 13:55. Показов 2340. Ответов 25
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Всем привет!Столкнулся с проблемой,программа не хочет рисовать отрезок.В консольном окне появляется надпись:
Process returned -1073741819 (0xC0000005) execution time : 3.402 s"
Но графическое окно не появляется.Использую CodBlocks.Что делать?




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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <stdio.h>
#include <graphics.h>
 
void BrezLine(POINT from, POINT to, COLORREF color)
{
    int x, y, xend, yend, s, dx, dy, d, inc1, inc2;
    int x1, x2, y1, y2;
 
    x1 = from.x;
    x2 = to.x;
    y1 = from.y;
    y2 = to.y;
    dx = abs(x2-x1);
    dy = abs(y2-y1);
 
    if(dx > dy)
    {
        inc1 = 2*dy;
        inc2 = 2*(dy-dx);
        d = 2*dy-dx;
 
        if(x1 < x2)
        {
            x = x1; y = y1; xend = x2;
            (y1 < y2) ? s = 1 : s = -1;
        }
        else
        {
            x = x2;
            y = y2;
            xend = x1;
            (y1 > y2) ? s = 1 : s = -1;
        }
 
        putpixel(x,y,color);
 
        while(x < xend)
        {
            x++;
            if(d > 0)
            {
                y += s;
                d += inc2;
            }
            else d += inc1;
            putpixel(x,y,color);
        }
    }
    else
    {
        inc1 = 2*dx;
        inc2 = 2*(dx-dy);
        d = 2*dx-dy;
 
        if(y1 < y2)
        {
            y = y1; x = x1; yend = y2;
            (x1 < x2) ? s = 1 : s = -1;
        }
        else
        {
            y = y2;
            x = x2;
            yend = y1;
            (x1 > x2) ? s = 1 : s = -1;
        }
 
        putpixel(x,y,color);
 
        while(y < yend)
        {
            y++;
            if(d > 0)
            {
                x += s;
                d += inc2;
            }
            else d += inc1;
            putpixel(x,y,color);
        }
    }
}
 
int main()
{
    POINT f, t, q, w;
    f.x = 45; f.y = -98;
    t.x = 700; t.y = 400;
 
    initwindow(800,600);
    BrezLine(f,t,0x00ff00b2);
 
    getch();
    closegraph();
    return 0;
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
21.03.2019, 13:55
Ответы с готовыми решениями:

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

Vector Graphics ActiveX - множество ошибок при использовании
Уважаемые коллеги, кто-то работал с сием чудом? Vector Graphics ActiveX Сайт...

При загрузке Windows открывается окно cmd и открывается сайт в браузере
Доброго времени суток. Проблемка тут случилась. Была скачана какая-то прога непонятная. Та...

При загрузке Windows открывается окно cmd и открывается сайт в хроме
После загрузки Windows7 открывается окно cmd и открывается сайт в хроме.

25
5158 / 2770 / 465
Регистрация: 05.10.2013
Сообщений: 7,321
Записей в блоге: 147
24.03.2019, 14:48 21
Author24 — интернет-сервис помощи студентам
My Original Message in English

Цитата Сообщение от 8Observer8 Посмотреть сообщение
Вам нужно распаковать, прежде чем вы откроете файл ".sln".
No, it is not that problem. It is something with your Visual Studio. What version of Visual Studio?


Translate Google Result:

Цитата Сообщение от 8Observer8 Посмотреть сообщение
Вам нужно распаковать, прежде чем вы откроете файл ".sln".
Нет, это не та проблема. Это что-то с вашей Visual Studio. Какая версия Visual Studio?
0
5158 / 2770 / 465
Регистрация: 05.10.2013
Сообщений: 7,321
Записей в блоге: 147
24.03.2019, 14:53 22
My Original Message in English

Another good solution for this task is a tool called Canvas API: link on English documentation. This API allows you to write a code in TypeScript. A code in TypeScript is logically similar on C++. Canvas API allows you to draw on the HTML5 <canvas> element. In this case your solutions will be accessible from different platforms like: Mac, Linux, Windows and mobile devices. You can post your solution on a sandbox like Plunker. I like Plunker more than JSFiddle or CodePen because Plunker allows to post a multi file solutions.

Compare line by line how it is similar on wxWidgets:
C++
1
2
3
4
5
6
    gc->SetPen( *wxRED_PEN );
    wxGraphicsPath path = gc->CreatePath();
    path.MoveToPoint(50.0, 50.0);
    path.AddLineToPoint(100.0, 100.0);
    path.AddLineToPoint(250.0, 150.0 );
    gc->StrokePath(path);
Javascript
1
2
3
4
5
6
    gc.strokeStyle = "red";
    gc.beginPath();
    gc.moveTo(50, 50);
    gc.lineTo(100, 100);
    gc.lineTo(250, 150);
    gc.stroke();
Click to run the example in sandbox

You will not found such tool in C++ where you can post your code with graphics where you can run it online and where you can copy the example to your account. I think Plunker + TypeScript is good tool to teach student of computer graphics and general programming.

main.ts

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
function main()
{
    let canvas = document.getElementById("renderCanvas");
    let gc = canvas.getContext("2d");
    
    gc.strokeStyle = "red";
    gc.beginPath();
    gc.moveTo(50, 50);
    gc.lineTo(100, 100);
    gc.lineTo(250, 150);
    gc.stroke();
}
index.html

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
 
<head>
    <link rel="stylesheet" href="style.css">
    <title>Line Strip</title>
</head>
 
<body onload="main()">
    <canvas id="renderCanvas" width="256" height="256"></canvas>
    <script src="main.js"></script>
</body>
 
</html>
style.css

CSS
1
2
3
4
#renderCanvas {
    border: 1px green solid;
    background-color: #c9c9c9;
}


Translate Google Result:

Другим хорошим решением для этой задачи является инструмент под названием Canvas API:ссылка на русскую документацию. Этот API позволяет вам писать код на TypeScript. Код в TypeScript логически похож на C ++. Canvas API позволяет рисовать на элементе HTML5 <canvas>. В этом случае ваши решения будут доступны с разных платформ, таких как: Mac, Linux, Windows и мобильные устройства. Вы можете разместить свое решение в песочнице как Plunker. Мне нравится Plunker больше, чем JSFiddle или CodePen, потому что Plunker позволяет публиковать многофайловые решения на TypeScript.

Сравните построчно, как это похоже на wxWidgets:
C++
1
2
3
4
5
6
    gc->SetPen( *wxRED_PEN );
    wxGraphicsPath path = gc->CreatePath();
    path.MoveToPoint(50.0, 50.0);
    path.AddLineToPoint(100.0, 100.0);
    path.AddLineToPoint(250.0, 150.0 );
    gc->StrokePath(path);
Javascript
1
2
3
4
5
6
    gc.strokeStyle = "red";
    gc.beginPath();
    gc.moveTo(50, 50);
    gc.lineTo(100, 100);
    gc.lineTo(250, 150);
    gc.stroke();
Click to run the example in sandbox

Название: Lines_CanvasAPITypeScript.png
Просмотров: 36

Размер: 1.0 Кб

Вы не найдете такого инструмента в C ++, где вы можете разместить свой код с графикой, где вы можете запустить его онлайн и где вы можете скопировать пример в свою учетную запись. Я думаю, что Plunker + TypeScript - хороший инструмент для обучения студентов компьютерной графике и общему программированию.

main.ts

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
function main()
{
    let canvas = document.getElementById("renderCanvas");
    let gc = canvas.getContext("2d");
    
    gc.strokeStyle = "red";
    gc.beginPath();
    gc.moveTo(50, 50);
    gc.lineTo(100, 100);
    gc.lineTo(250, 150);
    gc.stroke();
}
index.html

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
 
<head>
    <link rel="stylesheet" href="style.css">
    <title>Line Strip</title>
</head>
 
<body onload="main()">
    <canvas id="renderCanvas" width="256" height="256"></canvas>
    <script src="main.js"></script>
</body>
 
</html>
style.css

CSS
1
2
3
4
#renderCanvas {
    border: 1px green solid;
    background-color: #c9c9c9;
}
0
171 / 104 / 25
Регистрация: 17.10.2010
Сообщений: 1,146
24.03.2019, 15:16 23
Yes of course! I unzipped the archive into the folder and then I ran the ".sln". file. Конечно! Я сначала распаковал архив в папку, а затем запустил файл ".sln". I need help?????!!!!!!!

Добавлено через 5 минут
Где ошибка??? Или нужно Visual Studio 2016-2018??????

Добавлено через 10 минут
Мой версия Visual Studio 2015. Какой нужен????? На сколько я понимать все библиотеки и хедеры в в ашем архиве. Я распаковал ваш архив в одну папку и запустил файл ".sln" и посыпались ошибке как на скриншоте. У вас там полно библиотек и хедеров, ко орые нужно подключить. Как и всех одновременно подключить, а не по отдельности????? Или нужна другая среда разработки??????? Help me please!!!!

Добавлено через 12 секунд
Мой версия Visual Studio 2015. Какой нужен????? На сколько я понимать все библиотеки и хедеры в в ашем архиве. Я распаковал ваш архив в одну папку и запустил файл ".sln" и посыпались ошибке как на скриншоте. У вас там полно библиотек и хедеров, ко орые нужно подключить. Как и всех одновременно подключить, а не по отдельности????? Или нужна другая среда разработки??????? Help me please!!!!
0
5158 / 2770 / 465
Регистрация: 05.10.2013
Сообщений: 7,321
Записей в блоге: 147
24.03.2019, 15:23 24
My Original Message in English
Цитата Сообщение от isaak Посмотреть сообщение
Мой версия Visual Studio 2015.
I have Visual Studio 2015 too. I do not know how to solve this error. You need to search in the Internet the text of the error: this character is not allowed as a first character of an identifier


Translate Google Result:

Цитата Сообщение от isaak Посмотреть сообщение
Мой версия Visual Studio 2015.
У меня тоже Visual Studio 2015. Я не знаю, как решить эту ошибку. Вам нужно поискать в интернете текст ошибки: this character is not allowed as a first character of an identifier
0
3881 / 2479 / 418
Регистрация: 09.09.2017
Сообщений: 10,869
25.03.2019, 10:59 25
Ладно, раз уж пошло развлечение с более-менее современными средствами, вот еще на SDL2 + OpenGL1. Конечно, OpenGL1 устарел, зато для понимания проще
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
60
61
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdio.h>
#include <SDL2/SDL.h>
 
SDL_Window *window; //объект окна, нужен для взаимодействия с оконной системой ОС
SDL_GLContext context; //объект OpenGL. Теоретически, все вызовы должны осуществляться его методами, но напрямую - проще
 
const unsigned long Xmin = 0;
const unsigned long Ymin = 0;
const unsigned long Xmax = 800;
const unsigned long Ymax = 600;
 
#define BG_COLOR 1,1,1
#define FG_COLOR 0,0,0
#define GRID_COLOR 0,1,0
 
void draw(){
  glBegin(GL_LINE_STRIP);
  glColor3f(FG_COLOR);
  
  glVertex2f(45, -98);
  glVertex2f(700, 400);
  
  glEnd();
}
 
char update(){
  SDL_Event event;
  while(SDL_PollEvent(&event)){
    if(event.type == SDL_QUIT){return false;}
    if(event.type == SDL_KEYUP){return false;}
  }
  return true;
}
 
int main(int argc, char **argv){
  window = SDL_CreateWindow("Open GL + SDL window",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,
                            800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
  if(window == NULL){goto FINISH;} //не удалось создать окно - ошибка (на модели не обрабатывается)
  context=SDL_GL_CreateContext(window);
  if(context == NULL){goto FINISH;} //не удалось привязать OpenGL к окну - ошибка (не обрабатывается)
  //настройки OpenGL
  glClearColor(BG_COLOR,0);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(Xmin,Xmax, Ymin,Ymax);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  
  while(update()){
    glClear(GL_COLOR_BUFFER_BIT);
    draw();
    glFlush();
    SDL_GL_SwapWindow(window);
  }
FINISH:
  if(context){SDL_GL_DeleteContext(context); context=0;}
  if(window){SDL_DestroyWindow(window); window=0;}
  SDL_Quit();
}
0
5158 / 2770 / 465
Регистрация: 05.10.2013
Сообщений: 7,321
Записей в блоге: 147
25.03.2019, 11:56 26
My Original Message in English

Цитата Сообщение от COKPOWEHEU Посмотреть сообщение
OpenGL1 устарел, зато для понимания проще
It is subjective: OenGL проблы с текстурами

If you do not want to study modern OpenGL then SDL2 built-in API for drawing primitives is more simple to understand and more shorter to use than deprecated OpenGL. SDL2 build-in API are not legacy.

I took an example how to draw lines from the official documentation: https://wiki.libsdl.org/SDL_RenderDrawLines

isaak, please, try to run this Visual Studio project: Lines_SDL2Cpp.zip (all libraries are included and set up)

Название: Lines_SDL2Cpp.png
Просмотров: 32

Размер: 1.8 Кб

main.cpp

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
#include "SDL.h"
 
#define POINTS_COUNT 4
 
static SDL_Point points[POINTS_COUNT] = {
    { 50, 50 },
    { 100, 25 },
    { 150, 100 },
    { 200, 0 }
};
 
int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO) == 0)
    {
        SDL_Window* window = NULL;
        SDL_Renderer* renderer = NULL;
 
        if (SDL_CreateWindowAndRenderer(200, 200, 0, &window, &renderer) == 0)
        {
            SDL_bool done = SDL_FALSE;
 
            while (!done)
            {
                SDL_Event event;
 
                SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
                SDL_RenderClear(renderer);
 
                SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE);
                SDL_RenderDrawLines(renderer, points, POINTS_COUNT);
                SDL_RenderPresent(renderer);
 
                while (SDL_PollEvent(&event))
                {
                    if (event.type == SDL_QUIT)
                    {
                        done = SDL_TRUE;
                    }
                }
            }
        }
 
        if (renderer)
        {
            SDL_DestroyRenderer(renderer);
        }
        if (window)
        {
            SDL_DestroyWindow(window);
        }
    }
    SDL_Quit();
    return 0;
}


Translate Google Result:

Цитата Сообщение от COKPOWEHEU Посмотреть сообщение
OpenGL1 устарел, зато для понимания проще
Это субъективно: OenGL проблы с текстурами

Если вы не хотите изучать современный OpenGL, то встроенный API-интерфейс SDL2 для рисования примитивов более прост для понимания и более короток в использовании, чем устаревший OpenGL. Встроенный API SDL2 не является устаревшим.

Я взял пример, как рисовать линии из официальной документации: https://wiki.libsdl.org/SDL_RenderDrawLines

isaak, пожалуйста, попробуйте запустить этот проект Visual Studio: Lines_SDL2Cpp.zip (все библиотеки включены и настроены)

Название: Lines_SDL2Cpp.png
Просмотров: 32

Размер: 1.8 Кб

main.cpp

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
#include "SDL.h"
 
#define POINTS_COUNT 4
 
static SDL_Point points[POINTS_COUNT] = {
    { 50, 50 },
    { 100, 25 },
    { 150, 100 },
    { 200, 0 }
};
 
int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO) == 0)
    {
        SDL_Window* window = NULL;
        SDL_Renderer* renderer = NULL;
 
        if (SDL_CreateWindowAndRenderer(200, 200, 0, &window, &renderer) == 0)
        {
            SDL_bool done = SDL_FALSE;
 
            while (!done)
            {
                SDL_Event event;
 
                SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
                SDL_RenderClear(renderer);
 
                SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE);
                SDL_RenderDrawLines(renderer, points, POINTS_COUNT);
                SDL_RenderPresent(renderer);
 
                while (SDL_PollEvent(&event))
                {
                    if (event.type == SDL_QUIT)
                    {
                        done = SDL_TRUE;
                    }
                }
            }
        }
 
        if (renderer)
        {
            SDL_DestroyRenderer(renderer);
        }
        if (window)
        {
            SDL_DestroyWindow(window);
        }
    }
    SDL_Quit();
    return 0;
}
0
25.03.2019, 11:56
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.03.2019, 11:56
Помогаю со студенческими работами здесь

При загрузке Windows открывается окно cmd и открывается сайт в браузере
Здравствуйте! Помогите, пожалуйста! При загрузке компьютера открывается окно cmd и загружается...

При загрузке Windows открывается окно cmd и открывается сайт в браузере
Добрый вечер. У меня такая проблема. При включении компьютера открывается пустая командная строка,...

При загрузке Windows открывается окно cmd и открывается сайт
Здравствуйте! При включении компьютера, открывается окно браузера яндекс и сразу открывается...

При загрузке Windows открывается окно cmd и открывается какой то сайт в браузере
Всем привет, подскажите как исправить &quot;При загрузке Windows открывается окно cmd и открывается сайт...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
26
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru