Выполняю задание из учебника Страуструпа. Столкнулся с 3-мя проблемами. Комментарии на английском из другой программы.
1) Непонятно как написать буфер из пользовательского класса со стринг. (строка 54) Я не понимаю что нужно написать чтобы он был пустым.
2) Как поместить в конец вектора char значение char из пользовательского класса (строка 156)
3) Какие-то проблемы с gs.get (строка 95, 144) В программе из учебника таких проблем нет. Приложил ее в конце
Суть в том чтобы проверить грамматику введенного предложения. Пример предложения: существительное+глагол, артикль+существительное+глагол. В общем не важно, проверка все равно не сделана.
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
| #include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
using namespace std;
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
inline void error(const string& s)
{
throw runtime_error(s);
}
class Grammar {
public:
char kind; // what kind of token
string Wd; // for numbers: a value
Grammar(char ch, string w) // make a Token from a char and a double
:kind(ch), Wd(w) { }
};
class Grammar_stream {
public:
Grammar_stream();
Grammar get(); // get a Token (get() is defined elsewhere)
void putback(Grammar w);
private:
bool full; // is there a Token in the buffer?
Grammar buffer; // here is where we keep a Token put back using putback()
};
// The constructor just sets full to indicate that the buffer is empty:
Grammar_stream::Grammar_stream()
:full(false), buffer(' ') // no Token in buffer
{
}
// The putback() member function puts its argument back into the Token_stream's buffer:
void Grammar_stream::putback(Grammar w)
{
if (full) error("putback() into a full buffer");
buffer = w; // copy t to buffer
full = true; // buffer is now full
}
//------------------------------------------------------------------------------
Grammar Grammar_stream::get()
{
if (full) { // do we already have a Token ready?
// remove token from buffer
full = false;
return buffer;
}
string s;
cin >> s; // note that >> skips whitespace (space, newline, tab, etc.)
if (s == ".")
return Grammar('q', s);
vector<string> article = { "the", "a", "an" };
for (int i = 0; i < article.size(); ++i)
{
if (s == article[i])
return Grammar('a', s);
}
return Grammar(' ', s);
}
Grammar_stream gs;
///////////////////////////////////////////////////////////////////////////////////////
Grammar noun()
{
Grammar word = gs.get;
if (word.kind == ' ')
{
vector<string> noun = { "birds", "fish", "C++" };
for (int i = 0; i < noun.size(); ++i)
if (word.Wd == noun[i])
return Grammar('n', word.Wd);
}
return word;
}
Grammar verd()
{
Grammar word = noun();
if (word.kind == ' ')
{
vector<string> verb = { "rules", "fly", "swim" };
for (int i = 0; i < verb.size(); ++i)
if (word.Wd == verb[i])
return Grammar('v', word.Wd);
}
return word;
}
Grammar league()
{
Grammar word = verd();
if (word.kind == ' ')
{
vector<string> league = { "and", "or", "but" };
for (int i = 0; i < league.size(); ++i)
if (word.Wd == league[i])
return Grammar('l', word.Wd);
}
error("Слово неизвестно");
}
//программа определяет корректность предложения относительно грамматики английского языка
int main()
try
{
setlocale(LC_ALL, "Russian");
cout << "Введите предложение заканчивающееся ' .'";
vector<char> sentence;
while (cin)
{
while (cin)
{
Grammar word_left = gs.get; //берем из потока ввода слово для проверки конца предложения и смотрим его тип
if (word_left.kind == 'q')
{
cout << "Конец предложения\n"; //конец ввода предложения
keep_window_open();
break;
}
else
{
gs.putback(word_left); //ложим его назазад
}
Grammar word = league(); //определяем тип слова из потока ввода
sentence.push_back(word.kind()); //записываем в вектор последовательность типов слов для проверки грамматики
}
}
keep_window_open();
return 0;
}
catch (exception& e) {
cerr << "error: " << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops: unknown exception!\n";
keep_window_open();
return 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
255
256
257
258
259
260
| #include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
using namespace std;
//программа кулькулятор
inline void error(const string& s)
{
throw runtime_error(s);
}
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
inline void keep_window_open(string s)
{
if (s == "") return;
cin.clear();
cin.ignore(120, '\n');
for (;;) {
cout << "Please enter " << s << " to exit\n";
string ss;
while (cin >> ss && ss != s)
cout << "Please enter " << s << " to exit\n";
return;
}
}
class Token {
public:
char kind; // what kind of token
double value; // for numbers: a value
Token(char ch) // make a Token from a char
:kind(ch), value(0) { }
Token(char ch, double val) // make a Token from a char and a double
:kind(ch), value(val) { }
};
//------------------------------------------------------------------------------
class Token_stream {
public:
Token_stream(); // make a Token_stream that reads from cin
Token get(); // get a Token (get() is defined elsewhere)
void putback(Token t); // put a Token back
private:
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token put back using putback()
};
//------------------------------------------------------------------------------
// The constructor just sets full to indicate that the buffer is empty:
Token_stream::Token_stream()
:full(false), buffer(0) // no Token in buffer
{
}
//------------------------------------------------------------------------------
// The putback() member function puts its argument back into the Token_stream's buffer:
void Token_stream::putback(Token t)
{
if (full) error("putback() into a full buffer");
buffer = t; // copy t to buffer
full = true; // buffer is now full
}
//------------------------------------------------------------------------------
Token Token_stream::get()
{
if (full) { // do we already have a Token ready?
// remove token from buffer
full = false;
return buffer;
}
char ch;
cin >> ch; // note that >> skips whitespace (space, newline, tab, etc.)
switch (ch) {
case '=': // for "print"
case 'x': // for "quit"
case '{': case '}':
case '(': case ')': case '+': case '-': case '*': case '/':
return Token(ch); // let each character represent itself
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '9':
{
cin.putback(ch); // put digit back into the input stream
double val;
cin >> val; // read a floating-point number
return Token('8', val); // let '8' represent "a number"
}
default:
error("Bad token");
}
}
//------------------------------------------------------------------------------
Token_stream ts; // provides get() and putback()
//------------------------------------------------------------------------------
double expression(); // declaration so that primary() can call expression()
//------------------------------------------------------------------------------
//работает со скобками { }
Token hooks()
{
Token t = ts.get();
switch (t.kind) {
case '{': // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != '}') error("'}' expected");
return Token('8', d);
}
case '(': case ')':
return t;
case '8': // we use '8' to represent a number
return t; // return the number's value
default:
error("hooks expected");
}
}
// работает с числами и скобками ( )
double primary()
{
Token t = hooks();
switch (t.kind) {
case '(': // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected");
return d;
}
case '8': // we use '8' to represent a number
return t.value; // return the number's value
default:
error("primary expected");
}
}
//------------------------------------------------------------------------------
// работает с *, /
double term()
{
double left = primary();
Token t = ts.get(); // get the next token from token stream
while (true) {
switch (t.kind) {
case '*':
{
left *= primary();
t = ts.get();
break;
}
case '/':
{
double d = primary();
if (d == 0) error("divide by zero");
left /= d;
t = ts.get();
break;
}
default:
ts.putback(t); // put t back into the token stream
return left;
}
}
}
//------------------------------------------------------------------------------
// работает с + и -
double expression()
{
double left = term(); // read and evaluate a Term
Token t = ts.get(); // get the next token from token stream
while (true) {
switch (t.kind) {
case '+':
left += term(); // evaluate Term and add
t = ts.get();
break;
case '-':
left -= term(); // evaluate Term and subtract
t = ts.get();
break;
default:
ts.putback(t); // put t back into the token stream
return left; // finally: no more + or -: return the answer
}
}
}
//------------------------------------------------------------------------------
int main()
try
{
setlocale(LC_ALL, "Russian");
cout << "Добро пожаловать в программу-калькулятор!\n" <<
"Вводите выражения с числами с плавающей точкой.\n\n" <<
"Программа умеет работать со скобками и операциями +, -, *, /.\n" <<
"Для получения результата введите '=' в конце выражения.\n\n";
double val = 0;
while (cin) {
Token t = ts.get();
if (t.kind == 'x') break; // 'q' for quit
if (t.kind == '=') // ';' for "print now"
cout << "=" << val << '\n';
else
ts.putback(t);
val = expression();
}
keep_window_open();
}
catch (exception& e) {
cerr << "error: " << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops: unknown exception!\n";
keep_window_open();
return 2;
} |
|