Форум программистов, компьютерный форум, киберфорум
C для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.75/4: Рейтинг темы: голосов - 4, средняя оценка - 4.75
27 / 27 / 9
Регистрация: 31.01.2013
Сообщений: 89
1

Расширьте возможности dcl

29.09.2013, 17:01. Показов 810. Ответов 1
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Упражнение 5.20. Расширьте возможности dcl, чтобы dcl обрабатывала объявления с типами аргументов
функции, квалификаторами вроде const и т.п.

Вроде все правильно, но в то же время при работе постоянно выдает сообщения из функции errmesg и syntax error

Кликните здесь для просмотра всего текста
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
#define MAXTOKEN 100
#define BUFSIZE 100
 
enum {NAME, PARENS, BRACKETS};
enum {NO, YES};
 
void dcl(void);         //parse a declarator
void dirdcl(void);      //parse a direct declarator
int gettoken(void);
void paramdcl(void);    //declarator analysis with parameters 
void declspec(void);    //specification declaration
int typespec(void);     //type specifier
int typedesc(void);     //descriptor type
int getch(void);        //get a (possibly pushed-back) character
void ungetch(int c);    //push character back on input
void errmesg(char *msg); //error message
 
int tokentype;              //type of last token
char token[MAXTOKEN];       //last token string
char name[MAXTOKEN];        //identifier name
char datatype[MAXTOKEN];    //data type = char, int, etc.
char buf[BUFSIZE];          //buffer for ungetch;
char out[1000];
int errtoken = NO;
int errbrack = NO;
 
 
/* convert declaration to words */
int main()
{
    while(gettoken() != EOF)        //1st token on line
    {
        strcpy(datatype, token);    //is the datatype
        out[0] = '\0';
        dcl();      //parse rest of line
        if(tokentype != '\n')
            printf("syntax error\n");
        printf("%s: %s %s\n", name, out, datatype);
    }
    return 0;
}
 
/* dcl: parse a declarator */
void dcl(void)
{
    int ns;
    
    for(ns = 0; gettoken() == '*';) //count stars
        ns++;
    dirdcl();
    while(ns-- > 0)
        strcat(out, " pointer to");
}
 
/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
    int type;
    
    if(tokentype == '(') //(dcl)
    {
        dcl();
        if(tokentype != ')')
            errmesg("error: missing )\n");
    }
    else if(tokentype == NAME) //variable name
    {
        if(name[0] == '\0')
            strcpy(name, token);
    }
    else
        errtoken = YES;
    while((type = gettoken()) == PARENS || type == BRACKETS || type == '(')
        if(type == PARENS)
            strcat(out, " function returning");
        else if(type == '(')
        {
            strcat(out, " function taking");
            paramdcl();
            strcat(out, " and returning");
        }
        else
        {
            strcat(out, " array");
            strcat(out, token);
            strcat(out, " of");
        }
}
 
/* errmesg: error message */
void errmesg(char *msg)
{
    printf("%s", msg);
    errtoken = YES;
}
 
/* paramdcl: declarator analysis with parameters */
void paramdcl(void)
{
    do
    {
        declspec(); //specification declaration
    } while(tokentype == ',');
    if(tokentype != ')')
        errmesg("missing ) in declarator of parameters\n");
}
 
/* specification declaration */
void declspec(void)
{
    char temp[MAXTOKEN];
    
    temp[0] = '\0';
    gettoken();
    do
    {
        if(tokentype != NAME)
        {
            errtoken = YES;
            dcl();
        }
        else if(typespec() == YES) // type specifier
        {
            strcat(temp, " ");
            strcat(temp, token);
            gettoken();
        }
        else if(typedesc() == YES) //descriptor type
        {
            strcat(temp, " ");
            strcat(temp, token);
            gettoken();
        }
        else
            errmesg("error: unknown type in the parameter list\n");
    } while(tokentype != ',' && tokentype != ')');
    strcat(out, temp);
    if(tokentype == ',')
        strcat(out, ",");
}
 
/* type specifier */
int typespec(void)
{
    static char *types[] = {"char", "int", "void"};
    char *ptypes = token;
    int result, i;
    result = NO;
 
    for(i = 0; i < 3; i++)
        if(strcmp(ptypes, *(types + i)) != 0)
            result = NO;
        else
        {
            result = YES;
            return result;
        }
    return result;
        
}
 
/*  descriptor type */
int typedesc(void)
{
    static char *typed[] = {"const", "volatile"};
    char *ptd = token;
    
    int result, i;
    result = NO;
 
    for(i = 0; i < 2; i++)
        if(strcmp(ptd, *(typed + i)) != 0)
            result = NO;
        else
        {
            result = YES;
            return result;
        }
    return result;
}
 
int gettoken(void)
{
    int c;
 
    char *p = token;
    
    if(errtoken == YES)
    {
        errtoken = NO;
        return tokentype;
    }    
    while((c = getch()) == ' ' || c == '\t')
        ;
    if(c == '(')
    {
        if((c = getch()) == ')')
        {
            strcpy(token, "()");
            return tokentype = PARENS;
        }
        else
        {
            ungetch(c);
            return tokentype = '(';
        }
    }
    else if(c == '[')
    {
        for(*p++ = c; *p != ']';)
        {
            *p = getch();
            if(*p != ']')
            {
                if(*p == '\n' || *p == ')' || *p == '(')
                {
                    printf("error: missing ]\n");
                    ungetch(*p);
                    *p = ']';
                }
                else
                    p++;
            }
        }
        *++p = '\0';
        return tokentype = BRACKETS;
    }
    else if(isalpha(c))
    {
        for(*p++ = c; isalnum(c = getch());)
            *p++ = c;
        *p = '\0';
        ungetch(c);
        return tokentype = NAME;
    }
    else
        return tokentype = c;
}
 
int bufp = 0;
 
int getch(void) // get a (possibly pushed-back) character  
{
   int bufp = 0; //next free position in buf
   return (bufp > 0) ? buf[--bufp] : getchar();
}
 
void ungetch(int c) // push character back on input
{
    if(bufp >= BUFSIZE)
        printf("ungetch: too many characnters\n");
    else
        buf[bufp++] = c;
}


Прикрепляю отдельно файл.
Помогите помалуйста.
Вложения
Тип файла: zip 5.20.dcl.c.zip (1.7 Кб, 4 просмотров)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
29.09.2013, 17:01
Ответы с готовыми решениями:

Файлы. В цикле while…do расширьте файл за счет добавления новых значений
1. Составьте программу, которая создает файл из пяти значений типа real. Тип record не используйте....

где сохранить файл sld (слайд) для открытия в dcl форме?
как ни пытался открыть sld файл, отображается в dcl файле синий фон и все. Может надо конкретный...

При попытке написания диалогового окна DCL после точки с запятой включается комментирование
При попытке написания диалогового окна DCL после точки с запятой включается комментирование....

Расширьте класс Rectangle новым классом DrawableRect, у которого есть метод прорисовки draw(Graphics g) и поле outColor
Расширьте класс Rectangle новым классом DrawableRect, у которого есть метод прорисовки...

1
27 / 27 / 9
Регистрация: 31.01.2013
Сообщений: 89
03.10.2013, 14:09  [ТС] 2
Сам во всем разобрался, вот рабочий вариант.

Кликните здесь для просмотра всего текста
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
#define MAXTOKEN 100
 
enum {NAME, PARENS, BRACKETS};
enum {NO, YES};
 
void dcl(void);         //parse a declarator
void dirdcl(void);      //parse a direct declarator
void errmesg(char *); //error message
int gettoken(void);
 
int tokentype;              //type of last token
char token[MAXTOKEN];       //last token string
char name[MAXTOKEN];        //identifier name
char datatype[MAXTOKEN];    //data type = char, int, etc.
char out[1000];
int errtoken = NO;
int errbrack = NO;
 
/* convert declaration to words */
int main()
{
    while(gettoken() != EOF)        //1st token on line
    {
        strcpy(datatype, token);    //is the datatype
        out[0] = '\0';
        dcl();      //parse rest of line
        if(tokentype != '\n')
            printf("syntax error\n");
        printf("%s: %s %s\n", name, out, datatype);
    }
    return 0;
}
 
/* dcl: parse a declarator */
void dcl(void)
{
    int ns;
    
    for(ns = 0; gettoken() == '*';) //count stars
        ns++;
    dirdcl();
    while(ns-- > 0)
        strcat(out, " pointer to");
}
 
/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
    int type;
    void paramdcl(void);    //declarator analysis with parameters 
    
    if(tokentype == '(') //(dcl)
    {
        dcl();
        if(tokentype != ')')
            errmesg("error: missing )\n");
    }
    else if(tokentype == NAME) //variable name
    {
        if(name[0] == '\0')
            strcpy(name, token);
    }
    else
        errtoken = YES;
    while((type = gettoken()) == PARENS || type == BRACKETS || 
                                            type == '(')
        if(type == PARENS)
            strcat(out, " function returning");
        else if(type == '(')
        {
            strcat(out, " function taking");
            paramdcl();
            strcat(out, " and returning");
        }
        else
        {
            strcat(out, " array");
            strcat(out, token);
            strcat(out, " of");
        }
}
 
/* errmesg: error message */
void errmesg(char *msg)
{
    printf("%s", msg);
    errtoken = YES;
}
 
#include <stdlib.h>
 
void declspec(void);    //specification declaration
int typespec(void);     //type specifier
int typedesc(void);     //descriptor type
 
/* paramdcl: declarator analysis with parameters */
void paramdcl(void)
{
    do
    {
        declspec(); //specification declaration
    } while(tokentype == ',');
    if(tokentype != ')')
        errmesg("missing ) in declarator of parameters\n");
}
 
/* specification declaration */
void declspec(void)
{
    char temp[MAXTOKEN];
    
    temp[0] = '\0';
    gettoken();
    do
    {
        if(tokentype != NAME)
        {
            errtoken = YES;
            dcl();
        }
        else if(typespec() == YES) // type specifier
        {
            strcat(temp, " ");
            strcat(temp, token);
            gettoken();
        }
        else if(typedesc() == YES) //descriptor type
        {
            strcat(temp, " ");
            strcat(temp, token);
            gettoken();
        }
        else
            errmesg("error: unknown type in the parameter list\n");
    } while(tokentype != ',' && tokentype != ')');
    strcat(out, temp);
    if(tokentype == ',')
        strcat(out, ",");
}
 
/* type specifier */
int typespec(void)
{
    static char *types[] = {"char", "int", "void"};
    char *ptypes = token;
    int result, i;
   
    result = NO;
    for(i = 0; i < 3; i++)
        if(strcmp(ptypes, *(types + i)) == 0)
            return result = YES;
        else
            result = NO;
    return result;
        
}
 
/*  descriptor type */
int typedesc(void)
{
    static char *typed[] = {"const", "volatile"};
    char *ptd = token;
    int result, i;
    
    result = NO;
    for(i = 0; i < 2; i++)
        if(strcmp(ptd, *(typed + i)))
            return result = YES;
        else
            result = NO;
    return result;
}
 
int getch(void);        //get a (possibly pushed-back) character
void ungetch(int);    //push character back on input
 
int gettoken(void)
{
    int c;
    char *p = token;
    
    if(errtoken == YES)
    {
        errtoken = NO;
        return tokentype;
    }
    while((c = getch()) == ' ' || c == '\t')
        ;
    if(c == '(')
    {
        if((c = getch()) == ')')
        {
            strcpy(token, "()");
            return tokentype = PARENS;
        }
        else
        {
            ungetch(c);
            return tokentype = '(';
        }
    }
    else if(c == '[')
    {
        for(*p++ = c; *p != ']';)
        {
            *p = getch();
            if(*p != ']')
            {
                if(*p == '\n' || *p == ')' || *p == '(')
                {
                    printf("error: missing ]\n");
                    ungetch(*p);
                    *p = ']';
                }
                else
                    p++;
            }
        }
        *++p = '\0';
        return tokentype = BRACKETS;
    }
    else if(isalpha(c))
    {
        for(*p++ = c; isalnum(c = getch());)
            *p++ = c;
        *p = '\0';
        ungetch(c);
        return tokentype = NAME;
    }
    else
        return tokentype = c;
}
 
#define BUFSIZE 100
 
char buf[BUFSIZE];          //buffer for ungetch;
int bufp = 0;               //next free position in buf
 
int getch(void) // get a (possibly pushed-back) character  
{
   return (bufp > 0) ? buf[--bufp] : getchar();
}
 
void ungetch(int c) // push character back on input
{
    if(bufp >= BUFSIZE)
        printf("ungetch: too many characnters\n");
    else
        buf[bufp++] = c;
}
0
03.10.2013, 14:09
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
03.10.2013, 14:09
Помогаю со студенческими работами здесь

Ноутбук Асус Нет возможности разгона ОЗУ, а также в БИОС нет возможности отключения интегрированной графики
Здравствуйте! Ноутбук Асус м570дд. Стоит одноранговая память объемом 8гб от микрон. Чипсет x570dd....

Возможности c++
Всем привет! У меня 4 вопроса: 1)Нужно ли учить c++? 2)Возможности c++(то есть в что можно...

Возможности WP
Всем привет! Поставили такую задачу, нужно сделать сайт для группы в университете. возможности:...

Qt возможности
Гуру, помогите новичку на С++! Можете &quot;в двух словах&quot; рассказать о Qt (кросплатформенный С++)? ...


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

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