Textbook exercise

Hey everyone,

I'm having trouble figuring out where to start with one of the exercises at the end of this chapter.

Exercise: "The framing program writes the mostly blank lines that separate the borders from the greeting one character at a time. Change the program so that it writes all the spaces needed in a single output expression."

I've looked through the chapter and can't find anything that mentions how to do this. Any suggestions?

Here is the code I wrote:

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
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int pad = 0;
	cout << "Enter the desired padding: ";
	cin >> pad;
	cout << endl;
	const int rows = (pad * 2) +3;
	string name;
	cout << "Please enter your first name: ";
	cin >> name;
	const string greeting = "Hello, " + name;
	const string::size_type cols = greeting.size() + (pad * 2) + 2;
	cout << endl;
	for (int r = 0; r != rows; ++r) {
	        string::size_type c = 0;
		while (c != cols) {
			if (r == pad +1 && c == pad +1) {
				cout << greeting;
				c += greeting.size();
			}
			if ( r == 0 || r == rows - 1 || c == 0 || c == cols - 1)
				cout << "*";
			else
				cout << " ";
			++c;
		}
		cout << endl;
	}
	return 0;
}
What do you need your output to look like?
The output will be the same as the code above, it's just the exercise is challenging me to find a way to print all of the spaces in one output. I'm self-teaching myself through a textbook and this was one of the exercises at the end of the chapter. I couldn't find any information on how to do what it is asking so I decided to ask here. Thanks for the reply.
What if you appended spaces one at a time to a string, then output that string at the end?
How would one append just the spaces to a string? would it be like an array full of spaces? I'm sorry I don't understand, I'm still learning.
1
2
3
4
5
6
7
. . .

string Display = "Hello, ";
Display += "Bob";
cout << Display << endl;

. . .


Just an example of what he's getting at just in case you aren't familiar with it.

Edit: Wait, "JUST" the spaces? Odd...
Last edited on
Oh okay, I think I know what you guys are getting at now. I will work on that and see what I come up with. Thanks a lot both of you!

EDIT: Yeah, just the spaces. I will try my best. 頑張ります

Last edited on
Topic archived. No new replies allowed.