Reduce code length?

I've only been learning C++ for about a month now. I am currently rewriting this using functions (just learned it), but I was wondering if there are better ways of doing certain things to make coding easier/faster. My code totals about 500~ lines and I can't fit the whole program in here.

What the program does:
Allows the user to input 4 subjects and a grade for each subject. The program then calculates an average.

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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
  int main() 
{

	string msg1, msg2, msg3, msg4, msg5, msg6, error1;
	string subject1, subject2, subject3, subject4, name;
	int grade1 = 0, grade2 = 0, grade3 = 0, grade4 = 0, choiceInt1, choiceInt2;
	unsigned int average = 0;
	char choiceChar1, choiceChar2;
	bool choice1 = true;
	bool choice2 = true;
	const int MAX_STRING_SIZE = 20;
	error1 = "[ERROR: 001]";
	msg1 = "[Invalid Number]";
	msg2 = "[Invalid Answer]";
	msg3 = "[Subject successfully entered]";
	msg4 = "[Subject can not be over 20 characters]";
	msg5 = "[Grade successfully entered]";
	msg6 = "[Grade is not between 0 and 100]";

	cout << "[Average Grade Program 2.0]" << endl;

	while (name.size() == 0)
	{
		cout << "What is your name? ";
		getline(cin, name);

		if ((name.size() < MAX_STRING_SIZE))
		{
			cin.clear();
			cin.sync();
			cin.sync();
		}
		else if ((name.size() > MAX_STRING_SIZE))
		{
			cout << "Your name is too long!" << endl;
			name.clear();
			cin.clear();
			cin.sync();
			cin.sync();
		}
		else
		{
			cout << error1 << endl;
			cin.clear();
			cin.sync();
			cin.sync();
		}
	}
	
	cout << "Hello " + name + "!" << endl
		<< "This program will help you get an average of four subjects." << endl
		<< "To start, please select the first subject you would like to edit." << endl;

	while (choice1 == true)
	{
		cout << "----------------------" << endl 
			<< "1. " + subject1 << endl
			<< "2. " + subject2 << endl
			<< "3. " + subject3 << endl
			<< "4. " + subject4 << endl
			<< "5. I am done" << endl
			<< "----------------------" << endl;
		cin >> choiceInt1;
		cin.sync();
		cin.sync();

		if ((choiceInt1 > 0) && (choiceInt1 < 6) && (cin.good()))
		{
			if (choiceInt1 == 1)
			{
				cout << "My first subject is ";
				getline(cin, subject1);
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((subject1.size() < MAX_STRING_SIZE))
					{
						cout << msg3 << endl;
					}
					else if ((subject1.size() > MAX_STRING_SIZE))
					{
						cout << msg4 << endl;
						subject1.clear();
					}
				}
				else
				{
					cout << error1 << endl;
					subject1.clear();
					cin.clear();
				}
			}
			else if (choiceInt1 == 2)
			{
				cout << "My second subject is ";
				getline(cin, subject2);
				cin.sync();
				cin.sync();
				
				if (cin.good())
				{
					if ((subject2.size() < MAX_STRING_SIZE) && (cin.good()))
					{
						cout << msg3 << endl;
					}
					else if ((subject2.size() > MAX_STRING_SIZE) && (cin.good()))
					{
						cout << msg4 << endl;
						subject2.clear();
					}
				}
				else
				{
					cout << error1 << endl;
					subject2.clear();
					cin.clear();
				}
			}
			else if (choiceInt1 == 3)
			{
				cout << "My third subject is ";
				getline(cin, subject3);
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((subject3.size() < MAX_STRING_SIZE))
					{
						cout << msg3 << endl;
					}
					else if ((subject3.size() > MAX_STRING_SIZE))
					{
						cout << msg4 << endl;
						subject3.clear();
					}
				}
				else
				{
					cout << error1 << endl;
					subject3.clear();
					cin.clear();
				}
			}
			else if (choiceInt1 == 4)
			{
				cout << "My third subject is ";
				getline(cin, subject4);
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((subject4.size() < MAX_STRING_SIZE))
					{
						cout << msg3 << endl;
					}
					else if ((subject4.size() > MAX_STRING_SIZE))
					{
						cout << msg4 << endl;
						subject4.clear();
					}
				}
				else
				{
					cout << error1 << endl;
					subject4.clear();
					cin.clear();
				}
			}
			else if (choiceInt1 == 5)
			{
				cout << "Are you sure these are correct?" << endl;
				cin >> choiceChar1;
				cin.sync();
				cin.sync();

				if ((choiceChar1 != 'Y') || (choiceChar1 != 'y') || (choiceChar1 != 'N') || (choiceChar1 != 'n'))
				{

					if (cin.good())
					{
						if ((choiceChar1 == 'Y') || (choiceChar1 == 'y'))
						{
							choice1 = false;
						}
						else if ((choiceChar1 == 'N') || (choiceChar1 == 'n'))
						{
							continue;
						}
						else
						{
							cout << msg2 << endl;
							cin.clear();
						}
					}
					else
					{
						cout << msg2 << endl;
						cin.clear();
					}
				}
				else
				{
					cout << msg2 << endl;
					cin.clear();
				}
			}
			else
			{
				cout << error1 << endl;
				break;
			}
		}
		else
		{
			cout << msg1 << endl;
			cin.clear();		
		}
	}

	cout << "Please enter in your grades for each subject" << endl;

	while (choice2 == true)
	{
		cout << "----------------------" << endl 
			<< "1. " + subject1 + ": " << grade1 << endl
			<< "2. " + subject2 + ": " << grade2 << endl
			<< "3. " + subject3 + ": " << grade3 << endl
			<< "4. " + subject4 + ": " << grade4 << endl
			<< "5. I am done" << endl
			<< "----------------------" << endl;
		cin >> choiceInt2;
		cin.sync();
		cin.sync();

		if ((choiceInt2 > 0) && (choiceInt2 < 6) && (cin.good()))
		{
			if (choiceInt2 == 1)
			{
				cout << "What grade did you recieve in " + subject1 + "?" << endl;
				cin >> grade1;
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((grade1 > -1) && (grade1 < 101))
					{
						cout << msg5 << endl;
					}
					else
					{
						cout << msg6 << endl;
						grade1 = 0;
					}
				}
				else
				{
					cout << msg1 << endl;
					cin.clear();
					grade1 = 0;
				}
			}
			else if (choiceInt2 == 2)
			{
				cout << "What grade did you recieve in " + subject2 + "?" << endl;
				cin >> grade2;
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((grade2 > -1) && (grade2 < 101))
					{
						cout << msg5 << endl;
					}
					else
					{
						cout << msg6 << endl;
						grade2 = 0;
					}
				}
				else
				{
					cout << msg1 << endl;
					cin.clear();
					grade2 = 0;
				}
			}
			else if (choiceInt2 == 3)
			{
				cout << "What grade did you recieve in " + subject3 + "?" << endl;
				cin >> grade3;
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((grade3 > -1) && (grade3 < 101))
					{
						cout << msg5 << endl;
					}
					else
					{
						cout << msg6 << endl;
						grade3 = 0;
					}
				}
				else
				{
					cout << msg1 << endl;
					cin.clear();
					grade3 = 0;
				}
			}
			else if (choiceInt2 == 4)
			{
				cout << "What grade did you recieve in " + subject4 + "?" << endl;
				cin >> grade4;
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((grade4 > -1) && (grade4 < 101))
					{
						cout << msg5 << endl;
					}
					else
					{
						cout << msg6 << endl;
						grade4 = 0;
					}
				}
				else
				{
					cout << msg1 << endl;
					cin.clear();
					grade4 = 0;
				}
			}
			else if (choiceInt2 == 5)
			{
				cout << "Are you sure these are correct?" << endl;
				cin >> choiceChar2;
				cin.sync();
				cin.sync();

				if (cin.good())
				{
					if ((choiceChar2 == 'Y') || (choiceChar2 == 'y'))
					{
						choice2 = false;
					}
					else if ((choiceChar2 == 'N') || (choiceChar2 == 'n'))
					{
						continue;
					}
					else
					{
						cout << msg2 << endl;
						cin.clear();
					}
				}
				else
				{
					cout << msg2 << endl;
					cin.clear();
				}
			}
			else
			{
				cout << error1 << endl;
				cin.clear();
			}
		}
		else
		{
			cout << msg1 << endl;
			cin.clear();		
		}
	}
Replacing a few of your if/else() with switch() could shorten the code, but I believe what you really should be focusing on is repeated lines of code.

I see there are instructions that often come back in different if/else(). You could probably use loops so you would only need to write certain lines once and still get them to apply to different situations. It will involve some rethinking/rewriting though, and it might be tricky at times.

There might be other simpler solutions, but with my basic C++ knowledge that's all I can suggest for now.
Last edited on
I think you should be using arrays to hold the names of each subject and the grades. Also, the code makes liberal use of cin.sync() which unfortunately may not behave consistently from one compiler to another is is probably best avoided. Also cin.clear() is used unnecessarily many times.

Something like this, though in practice I would split this into separate functions, for getting the persons name, the subject names, the grades etc. This is kind of thrown together, and it still needs some tidying up and rework I think.

I used an array for the error messages, but I'm not convinced this is the best approach, as the code is easier to read if it is obvious which message is being output without having to refer to the definition to make sense of it - that's purely an issue of code legibility, not of functionality.
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
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <limits>

    using namespace std;

void emptyBuffer()
{
    // Empty input buffer
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}

int main()
{
    string msg[8] = {
        "[ERROR: 001]",
        "[Invalid Number]",
        "[Invalid Answer]",
        "[Subject successfully entered]",
        "[Subject can not be over 20 characters]",
        "[Grade successfully entered]",
        "[Grade is not between 0 and 100]",
        "Invalid Choice"
    };

    string numbers[4] = { "first", "second", "third", "fourth" };

    string name;
    string subject[4];
    int grade[4] = { 0 };

    int  choice;
    char ch;

    const unsigned int MAX_STRING_SIZE = 20;

    cout << "[Average Grade Program 2.0]" << endl;

    bool done = false;
    while (!done)
    {
        cout << "What is your name? ";
        getline(cin, name);

        if ((name.size() <= MAX_STRING_SIZE))
            done = true;
        else
            cout << "Your name is too long!" << endl;
    }

    cout << "Hello " + name + "!\n"
         << "This program will help you get an average of four subjects.\n"
         << "To start, please select the first subject you would like to edit." << endl;

    done = false;
    while (!done)
    {
        cout << "----------------------" << endl
            << "1. " + subject[0] << endl
            << "2. " + subject[1] << endl
            << "3. " + subject[2] << endl
            << "4. " + subject[3] << endl
            << "5. I am done" << endl
            << "----------------------" << endl;

        cin >> choice;

        if (!cin)
        {
            cin.clear();            // reset the error flags
            emptyBuffer();          // empty the input buffer
            cout << msg[1] << endl; // Invalid Number
            continue;
        }
        
        emptyBuffer();          // empty the input buffer
        
        if ((choice >= 1) && (choice <= 4))
        {
            int ix = choice - 1;

            cout << "My " << numbers[ix] << " subject is ";
            getline(cin, subject[ix]);

            if (subject[ix].size() <= MAX_STRING_SIZE)
            {
                cout << msg[3] << endl; // Subject successfully entered
            }
            else
            {
                cout << msg[4] << endl; // Subject can not be over 20 characters
            }
        }
        else if (choice == 5)
        {
            cout << "Are you sure these are correct?" << endl;
            cin >> ch;
            emptyBuffer();              // empty the input buffer

            ch = toupper(ch);

            if (ch == 'Y')
                done = true;
            else if (ch != 'N')
                cout << msg[2] << endl;  // Invalid Answer
        }
        else
        {
            cout << msg[7] << endl;      // Invalid Choice
        }
    }

    cout << "Please enter in your grades for each subject" << endl;

    done = false;
    while (!done)
    {
        cout << "----------------------" << endl
             << "1. " << subject[0] << ": " << grade[0] << endl
             << "2. " << subject[1] << ": " << grade[1] << endl
             << "3. " << subject[2] << ": " << grade[2] << endl
             << "4. " << subject[3] << ": " << grade[3] << endl
             << "5. I am done" << endl
             << "----------------------" << endl;
        cin >> choice;

        if (!cin)
        {
            cin.clear();            // reset the error flags
            emptyBuffer();          // empty the input buffer
            cout << msg[1] << endl; // Invalid Number
            continue;
        }
        
        emptyBuffer();              // empty the input buffer
        
        if ((choice >= 1) && (choice <= 4))
        {
            int ix = choice - 1;

            cout << "What grade did you receive in " + subject[ix] + "?" << endl;
            cin >> grade[ix];
            if (!cin)
            {
                cin.clear();            // reset the error flags
                emptyBuffer();          // empty the input buffer
                cout << msg[1] << endl; // Invalid Number
            }
            else
            {
                if ((grade[ix] >= 0) && (grade[ix] <= 100))
                {
                    cout << msg[5] << endl;  // Grade successfully entered
                }
                else
                {
                    cout << msg[6] << endl;  //  Grade is not between 0 and 100
                    grade[ix] = 0;
                }
            }
        }
        else if (choice == 5)
        {
            cout << "Are you sure these are correct?" << endl;
            cin >> ch;
            emptyBuffer();               // empty the input buffer

            ch = toupper(ch);

            if (ch == 'Y')
                done = true;
            else if (ch != 'N')
                cout << msg[2] << endl;   // Invalid Answer
        }
        else
        {
            cout << msg[7] << endl;      // Invalid Choice
        }        
    }

    return 0;
}

Last edited on
Topic archived. No new replies allowed.