#include <iostream>
#include <cstring>
#include <cstdlib>
using std::cin; using std::endl;
using std::cout; using std::string;
int main()
{
// ask for the person's name.
cout << "Enter your first name: ";
// read the name.
string name;
cin >> name;
// user defined blanks surrounding the greeting.
cout << "Enter the amount of padding you would like: ";
int pad;
cin >> pad;
// hold the message that we intend to write.
string greeting = "Hello, " + name + "!";
// the number of rows and columns to write.
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
// write a blank line to seperate the output from the input.
cout << endl;
// write "rows" rows of output.
// invariant: we have written "r" rows so far.
for(int r = 0; r != rows; ++r) {
string::size_type c = 0;
//invariant: we have written "c" characters so far in the current row.
while(c != cols) {
// is it time to write the greeting?
if(c == pad + 1 && r == pad + 1) {
cout << greeting;
c += greeting.size();
} else {
// are we on the border?
if (c == 0 || r == rows - 1 ||
r == 0 || c == cols - 1)
cout << "*";
else
cout << " ";
++c;
}
}
cout << endl;
}
system ("PAUSE");
return 0;
}
[edited by - Drevay on March 7, 2004 4:46:38 PM]
Argh. Problem number 2-4 in chapter 2 in Accelerated C++.
Ok, so, the problem is the question asks me to make the program presented in the chapter to print all of the spaces (the padding in between the Hello, [name]! and the border) in one expression instead of one at a time.
I've tried for an hour now and can't get it for the life of me.
Here's the source:
Yes, I've already done that, succeeded as long as the pad was 1, and 1 only. But as soon as it gets bigger, it screwed up.
Here's a sample output if
Anyway, help is much appreciated.
EDIT - Ignore the "^- where pad is 1" comment.
[edited by - Drevay on March 7, 2004 5:03:46 PM]
Here's a sample output if
pad
was two: clickay.Anyway, help is much appreciated.
EDIT - Ignore the "^- where pad is 1" comment.
[edited by - Drevay on March 7, 2004 5:03:46 PM]
Actually, it's this according to somebody on #gamedev (and it works fine) - this is just the main part of it:
I was confused since I thought I had to use a loop of some sort since it was in the chapter that introduced loops.
So happy. ^_^
[edited by - Drevay on March 7, 2004 5:18:39 PM]
std::cout<< std::string(greeting.size() + padlen *2 + 2, '*')<< std::endl
<<"*" + std::string(greeting.size() + padlen * 2, ' ') + "*"<< std::endl
<<"*" + std::string(padlen, ' ')< << "*" + std::string(greeting.size() + padlen * 2, ' ') + "*"<< std::endl
<< std::string(greeting.size() + padlen *2 + 2, '*')<< std::endl;
I was confused since I thought I had to use a loop of some sort since it was in the chapter that introduced loops.
So happy. ^_^
[edited by - Drevay on March 7, 2004 5:18:39 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement