Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.56/18: Рейтинг темы: голосов - 18, средняя оценка - 4.56
0 / 0 / 2
Регистрация: 03.01.2013
Сообщений: 113
1

Ошибка в коде

10.02.2013, 20:08. Показов 3429. Ответов 8
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте. В книге "ООП" Р. Лафоре, в главе 6 есть программка. Которая не хочет запускаться. Сперва набирал сам, после "долгих мучений" решил запустить оригинальный код посмотреть или запуститься - увы. Запускал в CB и в VS.
msoftcon.h и msoftcon.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
//cirles.cpp
//круги в качестве объектов
#include "msoftcon.h"      // Для функций консольной графики
 
 
class circle //графический объект "круг"
{
    protected:
    int xCo , yCo; //координаты центра
    int radius;
    color fillcolor; //цвет
    fstyle fillstyle; // стиль заполнения
    public:             //установка заполнения круга
    void set(int x, int y, int r, color fc, fstyle fs)
    {
        xCo = x;
        yCo = y;
        radius = r;
        fillcolor = fc;
        fillstyle = fs;
    }
    void draw()  //рисование круга
    {
        set_color(fillcolor); //установка заполнения и
        set_fill_style(fillstyle); //стиля заполнения
        draw_circle(xCo,yCo,radius); // рисование круга
    }
};
int main()
{
    init_graphics(); //инициализация графики
    circle c1;          // создание кругов
    circle c2;
    circle c3;
        //установка атрибутов
    c1.set(15,7,5,cBLUE, X_FILL);
    c2.set(41,12,7,cRED, O_FILL);
    c3.set(65,18,4,cGREEN, MEDIUM_FILL);
    c1.draw();      //рисование кругов
    c2.draw();
    c3.draw();
    set_cursor_pos(1,25); //нижний левый угол
    return 0;
}
Вот msoftcon.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
//msoftcon.h
//declarations for Lafore's console graphics functions
//uses Window's console functions
 
#ifndef _INC_WCONSOLE    //don't let this file be included
#define _INC_WCONSOLE    //twice in the same source file
 
#include <windows.h>     //for Windows console functions
#include <conio.h>       //for kbhit(), getche()
#include <math.h>        //for sin, cos
 
enum fstyle { SOLID_FILL, X_FILL,      O_FILL, 
              LIGHT_FILL, MEDIUM_FILL, DARK_FILL };
 
enum color {
   cBLACK=0,     cDARK_BLUE=1,    cDARK_GREEN=2, cDARK_CYAN=3, 
   cDARK_RED=4,  cDARK_MAGENTA=5, cBROWN=6,      cLIGHT_GRAY=7,
   cDARK_GRAY=8, cBLUE=9,         cGREEN=10,     cCYAN=11, 
   cRED=12,      cMAGENTA=13,     cYELLOW=14,    cWHITE=15 };
//--------------------------------------------------------------
void init_graphics();
void set_color(color fg, color bg = cBLACK);
void set_cursor_pos(int x, int y);
void clear_screen();
void wait(int milliseconds);
void clear_line();
void draw_rectangle(int left, int top, int right, int bottom);                    
void draw_circle(int x, int y, int rad);
void draw_line(int x1, int y1, int x2, int y2);
void draw_pyramid(int x1, int y1, int height);
void set_fill_style(fstyle);
#endif /* _INC_WCONSOLE */
это msoftcon.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//msoftcon.cpp
//provides routines to access Windows console functions
 
//compiler needs to be able to find this file
//in MCV++, /Tools/Options/Directories/Include/type path name
 
#include "msoftcon.h"
HANDLE hConsole;         //console handle
char fill_char;          //character used for fill
//--------------------------------------------------------------
void init_graphics()
   {
   COORD console_size = {80, 25};
   //open i/o channel to console screen
   hConsole = CreateFile("CONOUT$", GENERIC_WRITE | GENERIC_READ,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   0L, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0L);
   //set to 80x25 screen size
   SetConsoleScreenBufferSize(hConsole, console_size);
   //set text to white on black
   SetConsoleTextAttribute( hConsole, (WORD)((0 << 4) | 15) );
 
   fill_char = '\xDB';  //default fill is solid block
   clear_screen();
   }
//--------------------------------------------------------------
void set_color(color foreground, color background)
   {
   SetConsoleTextAttribute( hConsole, 
                        (WORD)((background << 4) | foreground) );
   }  //end setcolor()
 
/* 0  Black          8  Dark gray
   1  Dark blue      9  Blue
   2  Dark green     10 Green
   3  Dark cyan      11 Cyan
   4  Dark red       12 Red
   5  Dark magenta   13 Magenta
   6  Brown          14 Yellow
   7  Light gray     15 White
*/
//--------------------------------------------------------------
void set_cursor_pos(int x, int y)
   {
   COORD cursor_pos;              //origin in upper left corner
   cursor_pos.X = x - 1;          //Windows starts at (0, 0)
   cursor_pos.Y = y - 1;          //we start at (1, 1)
   SetConsoleCursorPosition(hConsole, cursor_pos);
   }
//--------------------------------------------------------------
void clear_screen()
   {
   set_cursor_pos(1, 25);
   for(int j=0; j<25; j++)
      putch('\n');
   set_cursor_pos(1, 1);
   }
//--------------------------------------------------------------
void wait(int milliseconds)
   {
   Sleep(milliseconds);
   }
//--------------------------------------------------------------
void clear_line()                    //clear to end of line
   {                                 //80 spaces
   //.....1234567890123456789012345678901234567890
   //.....0........1.........2.........3.........4 
   cputs("                                        ");
   cputs("                                        ");
   }
//--------------------------------------------------------------
void draw_rectangle(int left, int top, int right, int bottom) 
   {
   char temp[80];
   int width = right - left + 1;
 
   for(int j=0; j<width; j++)      //string of squares
      temp[j] = fill_char;   
   temp[j] = 0;                    //null
 
   for(int y=top; y<=bottom; y++)  //stack of strings 
      {
      set_cursor_pos(left, y);
      cputs(temp);
      }
   }
//--------------------------------------------------------------
void draw_circle(int xC, int yC, int radius)
   {
   double theta, increment, xF, pi=3.14159;
   int x, xN, yN;
 
   increment = 0.8 / static_cast<double>(radius);
   for(theta=0; theta<=pi/2; theta+=increment)  //quarter circle
      {
      xF = radius * cos(theta);  
      xN = static_cast<int>(xF * 2 / 1); //pixels not square
      yN = static_cast<int>(radius * sin(theta) + 0.5);
      x = xC-xN;
      while(x <= xC+xN)          //fill two horizontal lines
         {                       //one for each half circle
         set_cursor_pos(x,   yC-yN); putch(fill_char);  //top
         set_cursor_pos(x++, yC+yN); putch(fill_char);  //bottom
         }
      }  //end for
   }
//--------------------------------------------------------------
void draw_line(int x1, int y1, int x2, int y2)
   {
 
   int w, z, t, w1, w2, z1, z2;
   double xDelta=x1-x2, yDelta=y1-y2, slope;
   bool isMoreHoriz;
 
   if( fabs(xDelta) > fabs(yDelta) ) //more horizontal
      {
      isMoreHoriz = true;
      slope = yDelta / xDelta;
      w1=x1; z1=y1; w2=x2, z2=y2;    //w=x, z=y 
      }
   else                              //more vertical
      {
      isMoreHoriz = false;
      slope = xDelta / yDelta;
      w1=y1; z1=x1; w2=y2, z2=x2;    //w=y, z=x
      }
 
   if(w1 > w2)                       //if backwards w
      {
      t=w1; w1=w2; w2=t;             //   swap (w1,z1)
      t=z1; z1=z2; z2=t;             //   with (w2,z2)
      }
   for(w=w1; w<=w2; w++)            
      {
      z = static_cast<int>(z1 + slope * (w-w1));
      if( !(w==80 && z==25) )        //avoid scroll at 80,25
         {
         if(isMoreHoriz)
            set_cursor_pos(w, z);
         else
            set_cursor_pos(z, w);
         putch(fill_char);
         }
      }
   }
//--------------------------------------------------------------
void draw_pyramid(int x1, int y1, int height)
   {
   int x, y;
   for(y=y1; y<y1+height; y++)
      {
      int incr = y - y1;
      for(x=x1-incr; x<=x1+incr; x++)
         {
         set_cursor_pos(x, y);
         putch(fill_char);
         }
      }
   }
//--------------------------------------------------------------
void set_fill_style(fstyle fs)
   {
   switch(fs)
      {
      case SOLID_FILL:  fill_char = '\xDB'; break;
      case DARK_FILL:   fill_char = '\xB0'; break;
      case MEDIUM_FILL: fill_char = '\xB1'; break;
      case LIGHT_FILL:  fill_char = '\xB2'; break;
      case X_FILL:      fill_char = 'X';    break;
      case O_FILL:      fill_char = 'O';    break;
      }
   }
//--------------------------------------------------------------

Ошибки в CB:
Код
obj\Debug\main.o||In function `main':|
\Tetsnaf\main.cpp|30|undefined reference to `init_graphics()'|
\Tetsnaf\main.cpp|43|undefined reference to `set_cursor_pos(int, int)'|
\Tetsnaf\main.cpp|22|undefined reference to `set_color(color, color)'|
\Tetsnaf\main.cpp|23|undefined reference to `set_fill_style(fstyle)'|
\Tetsnaf\main.cpp|24|undefined reference to `draw_circle(int, int, int)'|
||=== Build finished: 5 errors, 0 warnings ===|
Ошибки в VS:
Код
1>------ Build started: Project: MyFirsProgram, Configuration: Debug Win32 ------
1>  Redaktor.cpp
1>Redaktor.obj : error LNK2005: _main already defined in Vararg.obj
1>Redaktor.obj : error LNK2019: unresolved external symbol "void __cdecl set_cursor_pos(int,int)" (?set_cursor_pos@@YAXHH@Z) referenced in function _main
1>Redaktor.obj : error LNK2019: unresolved external symbol "void __cdecl init_graphics(void)" (?init_graphics@@YAXXZ) referenced in function _main
1>Redaktor.obj : error LNK2019: unresolved external symbol "void __cdecl draw_circle(int,int,int)" (?draw_circle@@YAXHHH@Z) referenced in function "public: void __thiscall circle::draw(void)" (?draw@circle@@QAEXXZ)
1>Redaktor.obj : error LNK2019: unresolved external symbol "void __cdecl set_fill_style(enum fstyle)" (?set_fill_style@@YAXW4fstyle@@@Z) referenced in function "public: void __thiscall circle::draw(void)" (?draw@circle@@QAEXXZ)
1>Redaktor.obj : error LNK2019: unresolved external symbol "void __cdecl set_color(enum color,enum color)" (?set_color@@YAXW4color@@0@Z) referenced in function "public: void __thiscall circle::draw(void)" (?draw@circle@@QAEXXZ)
1>D:\Documents and Settings\Максим\мои документы\visual studio 2010\Projects\MyFirsProgram\Debug\MyFirsProgram.exe : fatal error LNK1120: 5 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Добавлено через 23 часа 50 минут
Нашел информацию что нужно юникод отключить. Сделал - не работает.
Возможно кто-то может хотя бы подсказать что это за ошибки ?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
10.02.2013, 20:08
Ответы с готовыми решениями:

Ошибка в коде (Ошибка сегментирования (core dumped)
Добрый день. Подскажите пожалуйста, где ошибка в коде? char ch; string s; ...

В чём ошибка.В коде там где коментарий там ошибка поучается.
#include &lt;iostream&gt; #include &lt;Windows.h&gt; using namespace std; class CMyString{ char *pStr;...

Ошибка в коде
Не могу найти ошибки в коде. Программа вылетает после ввода a. #include &lt;iostream&gt; void func...

В коде ошибка
Что здесь не так?

8
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
10.02.2013, 20:19 2
Скопировал ваш код в новый проект в VS2012. Единственное, что надо было исправить для успешной компиляции: в свойствах проекта поставить мульти-байтную кодировку, а в функции draw_rectangle в начале приписать int j; и убрать int в цикле for ниже.
0
0 / 0 / 2
Регистрация: 03.01.2013
Сообщений: 113
10.02.2013, 21:02  [ТС] 3
Цитата Сообщение от nonedark2008 Посмотреть сообщение
Скопировал ваш код в новый проект в VS2012. Единственное, что надо было исправить для успешной компиляции: в свойствах проекта поставить мульти-байтную кодировку, а в функции draw_rectangle в начале приписать int j; и убрать int в цикле for ниже.
Благодарю за комментарий. Сделал как вы сказали.
Уже понял что не так делал в самом начале.

Вот сейчас уже одна ошибка:
1>d:\documents and settings\максим\мои документы\visual studio 2010\projects\myfirsprogram\myfirsprogram\msoftcon.cpp(17): error C2664: 'CreateFileA' : cannot convert parameter 1 from 'const wchar_t [8]' to 'LPCSTR'

Нашел в интернете что якобы ошибка в функции init_graphics
строка hConsole = CreateFile(L"CONOUT$", GENERIC_WRITE | GENERIC_READ,

Нужно было добавить L. Добавил, но результата нету.
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
10.02.2013, 21:07 4
Цитата Сообщение от IvanInanovich Посмотреть сообщение
Вот сейчас уже одна ошибка:
В свойствах проекта в VS нужно кодировку сменить на мультибайтную.
Или L придется дописывать у каждой символьной строки, которая есть в проекте.
0
0 / 0 / 2
Регистрация: 03.01.2013
Сообщений: 113
10.02.2013, 21:14  [ТС] 5
Цитата Сообщение от nonedark2008 Посмотреть сообщение
В свойствах проекта в VS нужно кодировку сменить на мультибайтную.
Или L придется дописывать у каждой символьной строки, которая есть в проекте.
Project - > "имя проекта" property... -> configuration Properties -> General - > Сharacter set -> Use Multi-Bite Charakcter set. Правильно? Если да, то так и сделал. Не помогает(
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
10.02.2013, 21:22 6
Цитата Сообщение от IvanInanovich Посмотреть сообщение
Не помогает(
Что пишет компилятор?
0
0 / 0 / 2
Регистрация: 03.01.2013
Сообщений: 113
10.02.2013, 21:22  [ТС] 7
Цитата Сообщение от nonedark2008 Посмотреть сообщение
Что пишет компилятор?

1>d:\documents and settings\максим\мои документы\visual studio 2010\projects\myfirsprogram\myfirsprogram\msoftcon.cpp(17): error C2664: 'CreateFileA' : cannot convert parameter 1 from 'const wchar_t [8]' to 'LPCSTR'
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
10.02.2013, 21:24 8
Заархивируй проект и скинь сюда.
1
0 / 0 / 2
Регистрация: 03.01.2013
Сообщений: 113
10.02.2013, 21:32  [ТС] 9
Цитата Сообщение от nonedark2008 Посмотреть сообщение
Заархивируй проект и скинь сюда.
Перед cputs поставил нижний слеш (_cputs) и заработало. СВ сразу же указало на ошибки (на j про которое вы говорили, тоже показывало), а VS2010 показывал совершенно иное.

Спасибо большое что отозвались! Одна ошибка в книге, принесла незаменимый опыт ))
0
10.02.2013, 21:32
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
10.02.2013, 21:32
Помогаю со студенческими работами здесь

Ошибка в коде
if (x(тут показывает ошибку&quot;Значение должно быть допустимым для левостороннего значения&quot;) &gt;=0 &amp;&amp;...

Ошибка в коде!
Пишу в данное время на c++, только начал изучать его основы. Для поднятия своего уровня решил...

Ошибка в коде
Нужно вывести последнюю лексему из строки. Текст ошибки: error C2664: &quot;size_t strlen(const char...

Ошибка в коде
class Matrix { private: int size, i, j; int d, k, n; int **My_Array; int **p;...


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

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