2-4. 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.

already google this, but what I got is a bunch of headache...

so, I given up to this forum instread, hope can help, it's related to the code below,

#include <iostream>
#include <string>

// say what standard-library names we use
using std::cin;         using std::endl;
using std::cout;        using std::string;

int main()
{
    // ask for the person's name
    cout << "Please enter your first name: ";

    // read the name
    string name;
    cin >> name;

    // build the message that we intend to write
    const string greeting = "Hello, " + name + "!";

    // the number of blanks surrounding the greeting
    const int pad = 1;

    // 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 separate 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 (r == pad + 1 && c == pad + 1) {
                cout << greeting;
                c += greeting.size();
            } else {

                // are we on the border?
                if (r == 0 || r == rows - 1 ||
                    c == 0 || c == cols - 1)
                    cout << "*";
                else
                    cout << " ";
                ++c;
            }
        }

        cout << endl;
    }

    return 0;
}

Recommended Answers

All 15 Replies

I think it's asking you to fix the loop such that it doesn't print multiple spaces here:

// are we on the border?
                if (r == 0 || r == rows - 1 ||
                    c == 0 || c == cols - 1)
                    cout << "*";
                else
                    cout << " ";

doesn't print multiple spaces???

can give me more detail on how that happen??? @.@

it should accumulate and print the spaces all at once instead of one at a time.

Instead of outputting a SPACE, add it to a string.
Before outputting a *, output that string.
Be sure to reset (clear) the string after output.

i found a solution of this, from a website... =W="

i can't relate anything with
"it should accumulate and print the spaces all at once instead of one at a time."

or maybe the solution is wrong??

pls help!!!

btw, thnx 4 reply...

#include <iostream>
#include <string>

// say what standard-library names we use
using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
   // ask for the person's name
   cout << "Please enter your first name: ";

   // read the name
   string name;
   cin >> name;

   // build the message that we intend to write
   const string greeting = "Hello, " + name + "!";

   // the number of blanks surrounding the greeting
   const int pad = 5;

   // the number of rows and columns to write
   const int rows = pad * 2 + 3;
   const string::size_type cols = greeting.size() + pad * 2 + 2;

   // string of spaces equal in size to the padding between
   // the border and the greeting
   const string padding(pad, ' ');

   // string of spaces to fill the empty area between borders
   // above and below the greeting
   const string filler(greeting.size() + pad * 2, ' ');

   // write a blank line to separate 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 (r == pad + 1 && c == pad + 1) {
            cout << greeting;
            c += greeting.size();
         } else {

            // are we on the border?
            if (r == 0 || r == rows - 1 ||
                c == 0 || c == cols - 1) {
               cout << "*";
               ++c;
            } else {

               // are we on the greeting line?
               if (r == pad + 1) {

                  // output the padding
                  cout << padding;
                  c += padding.size();
               } else {

                  // output empty space between borders
                  cout << filler;
                  c += filler.size();
               }
            }
         }
      }

      cout << endl;
   }

   return 0;
}

I already gave you the solution. You still went elsewhere to use someone else's code. Is Accelerated C++ teaching you to steal other people's code to do the project or are you supposed to actually think and come up with your own solution?

I feel like retard now, lol

http://www.daniweb.com/software-development/cpp/threads/390165

maybe I just not understand how the original code works at the first place, try asking before, but hardly got any reply...

thus, I give up on that, and continue to answering the exercise given in the book, even though my answer just a bunch of random shot...

then, I check the answer by google other's answer...

whatsoever,
the real thing I confuse about question 2.4 is, does it forbid me using 'while loop' and 'for loop'???
because, that will make the program "write one character at a time"???

urgh, I try my best, building this program from scratch, still refer to the book, a lot...

I think I can do good in programming because I'm good in math, seems can't relate much on how to deal with this... x-(

need fast help! until then, I just continue research this book for some idea...

// "include" library that we need in program
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

//proceed directly into the program
 
/* 1. try writing basic input and output program first.
 * 2. then, procced for the receiving desired frame size from user.
 * 3. build the frame.
 * 4. write the program.
 */

int main()
{
    // (1. try writing basic input and output program first.)
    string ask_user = "Please write your name: ";
    cout << ask_user;

    string name;
    cin >> name;

    const string greeting = "Hello " + name + " !";
    cout << endl << greeting << endl;

    // (2. then, procced for the receiving desired frame size from user.)
    const string pady_ask = "Please insert amount of space to seperate greeting from bottom and top frame: ";
    cout << pady_ask;
    string pady_input;
    cin >> pady_input;

    const string padx_ask = "Please insert amount of space to seperate greeting from its side: ";
    cout << padx_ask;
    string padx_input;
    cin >> padx_input;
    
    // (3. build the frame.)
    const int rows = pady * 2 + 3;
    
    const string::size_type cols = greeting.size() + padx * 2 + 2;
    
    
    string cols_star(cols, '*');
    string cols_space(colsp, ' ');
    string rows_star(rows, '*');
    string rows_star(rowsp, ' ');
    
    // seperate result from statement
    cout << endl << endl << endl;
    
    // (4. write the program.)
    

    return 0;
}

hmm, hope can delete post before, utterly useless..

btw, this my code for "line of string"

note:-
padx refer to x plane which is horizontal
pady refer to y plane which is vertical

outer refer to top and bottom because compiler write program "horizontaly", so I consider top and bottom as "outer"

not writing the part where to write the program yet, still in doubt if this code work or not, btw, this my bedtime, so I stop here, see ya tomorrow... xD

// "include" library that we need in program
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

//proceed directly into the program

/* 1. try writing basic input and output program first.
 * 2. then, proceed for the receiving desired frame size from user.
 * 3. build the frame.
 * 4. write the program.
 */

int main()
{
    // (1. try writing basic input and output program first.)
    string ask_user = "Please write your name: ";
    cout << ask_user;

    string name;
    cin >> name;

    const string greeting = "Hello " + name + " !";
    cout << endl << greeting << endl;

    // (2. then, decide frame size for greeting.)
    const int pady = 1;
    const int padx = 2;

    // (3. build the frame.)
    // line of string for top and bottom
    const string::size_type outer = greeting.size() + padx * 2 + 2;
    string outer_star(outer, '*');

    // line of string for line between top and bottom
    const string::size_type inner = greeting.size() + padx * 2;
    const string inner_space(inner, ' ');
    const string inner_write = "*" + inner_space + "*";

    // line of string for line in middle where greeting written
    const string greet_space(padx, ' ');
    const string greet_write = "*" + greet_space + greeting + greet_space + "*";

    // seperate result from statement
    cout << endl << endl << endl;

    // (4. write the program.)
    cout << outer_star;

    // seperate result from "returned data"
    cout << endl << endl << endl;

    return 0;
}

sorry for bad grammar, don't expect much from non-native speaker... =3

You need to do a lot more desk work designing the program. You cannot design, write code, and think all while sitting in front of the computer.

Away from the computer, write down the description of the task one line (sentence) at a time.
Take the first sentence and break it down into smaller pieces, or tasks, that need to be done. Do this for each sentence until you have a list of individual tasks.
Put each small task into an order that makes sense so if you gave the list to someone they could draw the pattern just by following the instructions you gave them.
Now, look at each task -- write down an explanation of how it would be coded.

The above is how programming is really done. 80% of the work is non-computer designing and planning, 15% is typing in the code, 5% is looking for the typos when it doesn't compile.

Once you get it to compile, the last 90% is debugging. :icon_wink:
This is where you follow the program with your design and figure out where
1) the code doesn't follow what you designed
2) where the design was wrong

thnx, you are right. thought my 'desk job' is on the computer anyway, create blank file in the editor and turn it into a notepad; because my handwriting too ugly and I can't read what I already write/design for my program... xD

anyway, this is my 'desk job'

Main task :-
   - ask user name and put them into greeting.
   - build a frame desired by user.
     -> actually, ask the user how much space the greeting from the frame.
     -> put the greeting in the middle.
     -> makesure the output write a string rather than write characater one-by-one.


    Task :-
    * Ask user's name.
    - output a string literal to ask user's name.
    - receive user input which is their name.
    - put the input into a string 'name'.
    - build a string 'greeting' which is constant and put 'name'
      into it. (note: use "+" operator, which can't be used
                     if both  string literals or character)


    * Build a frame desired by user :-
    - seperate type of size into two which is vertical and horizontal:-
       > described horizontal as x plane and vertical as y plane.
       > create variable for the size which is 'objecty' and 'objectx'. (ex: 'pady' and 'padx')

    - ask user's input:-
       > output a string literal to ask user's desired frame size.
         -> output different string literal for each type of size.
       > put the input into an const int type variable named 'pady' and 'padx'.

    - build the frame based on user's input :-
       > because we want to put frame in the middle, so, space of top and bottom from greeting should be same.
         -> so, this would mean (pad * 2)
       > for horizontal
         -> the size of greeting included and affected the witdth of the frame, so use [greeting.size() + padx * 2]
            to make the of width size parallel with size of greeting itself.
         -> the size of a star is 1, while padx is space between frame and greeting, it's not include the star yet
            so we should use [greeting.size() + padx * 2 + 1 * 2], it's multiply by 2 because the star is on both side.
       > by above action, the width of frame completely formed.

       => continue to design line of string of width first before bothering onto vertical problem.
       > for top and bottom line.
         -> we consider them as "outer".
         -> using this code {std::string outer_star(outer, '*'} which is {std::string::size_type outer = greeting.size() + padx * 2 + 2}
         -> code above contain line of string of "*" same amount of character as in "outer", thanks to string::size_type function.

       > for line between top and bottom from greeting.
         -> we consider them as "inner"
         -> using this code {std::string inner_space(inner, ' ')} which is {std::string::size_type inner = greeting.size() + padx *2}
         -> then, using this one {std::string inner_space_write = "*" + inner_space + "*";}
         -> the first code above will write the inner space of the frame, the border "*" is written manually using string type, thus removing +2
            from the second code to fit in the star.

       > for line in the middle which is the greeting.
         -> we consider them as "greet"
         -> using this code {std::string greet_write = "*" + greet + greeting + greet + "*"} which is {std::string greet(padx, ' ')}
         -> the code above will write "*" as their border line and then space between greeting and frame desired by user, and then the greeting
            itself which fit in the middle
        // I don't know this code will work or not because the compiler forbid for both variable between "+" operator to be string literals or character
        // and btw, it's left associative, i hope there any alternative so that i can give out my expected result.

       => continue to design code for vertical formation of the greeting.
       > using if/for loop/while loop, and pady in the code.
       > using this code:-

const std::string::size_type writingy = pady * 2 + 3;

for (int y = 0; y !> writingy; ++y)
{
	if (y = 0 || y = writingy)
	{
	    cout << outer_star;
	}
	else
	{
	    if (y > 0 && y < (writingy / 2))
	    {
	        cout << inner_space_write;
	    }

	    else
	    {
	        if (y > (writingy / 2 + 1 && y < writngy)
            {
                cout << inner_space_write;
            }

            else
            {
                cout << greet_write;
            }
	    }
	}

	cout << endl;
}



        description :-
        => at line 64, the code is for arranging the vertical formation;
        > so that the line of rows of frame is in form of odd number;( * 2 and + 3 )
        > *2 also used for the space of top and bottom frame from the greeting.
        > put those code into one const string "writingy"

        => at line 66 to 94, the code is for writing and build up the frame and greeting;
        > "for" used so that it will produce loop for the programm until the function declared wrong;
        > "if" used to test the condition to be true or wrong, and the scope will continued until there nothing to write;
        > 'cout << endl;' used so that it will continue to the next line after the output written.


        ending:-
        > return 0; used as ermm format?!, whatever thing that I should do in which I do not know why.


FIN == THE END == I"M DONE

plss comment if possible...

AND, this is my code, tested and successfully compiled, all thanks to you... (^_^)

//exercise module, temporary(delete older exercise that was test before put new one)

// "include" library that we need in program
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

//proceed directly into the program

/* 1. receive name from user.
 * 2. then, procced for the receiving desired frame size from user.
 * 3. build the frame.
 * 4. write the program.
 */

int main()
{
    // (1. receive name from user.)
    cout << "Please write your name: ";

    string name;
    cin >> name;

    const string greeting = "Hello " + name + " !";

    // (2. then, procced for the receiving desired frame size from user.)
    const string pady_ask = "Please insert amount of space to seperate greeting from bottom and top frame: ";
    cout << pady_ask;
    int pady_input;
    cin >> pady_input;
    const int pady = pady_input;

    const string padx_ask = "Please insert amount of space to seperate greeting from its side: ";
    cout << padx_ask;
    int padx_input;
    cin >> padx_input;
    const int padx = padx_input;

    // (3. build the frame.)
    // line of string for top and bottom
    const string::size_type outer = greeting.size() + padx * 2 + 2;
    string outer_star(outer, '*');

    // line of string for line between top and bottom
    const string::size_type inner = greeting.size() + padx * 2;
    const string inner_space(inner, ' ');
    const string inner_write = "*" + inner_space + "*";

    // line of string for line in middle where greeting written
    const string greet_space(padx, ' ');
    const string greet_write = "*" + greet_space + greeting + greet_space + "*";

    // amount of line of string in the program
    const std::string::size_type writingy = pady * 2 + 3;

    // seperate result from statement
    cout << endl << endl << endl;

    // (4. write the program.)
    for (int y = 0; y != writingy; ++y)
    {
        if (y == 0 || y == writingy - 1)
        {
            cout << outer_star;
        }

        else
        {
            if (y > 0 && y < (writingy / 2))
            {
                cout << inner_write;
            }

            else
            {
                if (y > (writingy / 2) && y < writingy - 1)
                {
                    cout << inner_write;
                }

                else
                {
                    cout << greet_write;
                }
            }
        }

        cout << endl;

    }


    // seperate result from "returned data"
    cout << endl << endl << endl;

    return 0;
}

hmmm, there is another question puzzling me around, quote from Accelerated C++..

s + t

The result of this expression is an std::string that contains a copy of the
characters in s followed by a copy of the characters in t. Either s or t, but
not both, may be a string literal or a value of type char.

why does the compiler just validate this code anyway?

// line of string for line in middle where greeting written
    const string greet_space(padx, ' ');
    const string greet_write = "*" + greet_space + greeting + greet_space + "*";

Your code at line 3 is valid because the + operators associate left to right. The first thing it computes is, effectively const string tmpString1 = "*" + greet_space; which is valid because only the first argument is a string-literal. Then it does const string tmpString2 = tmpString1 + greeting; and so on, each of which works because the first paramater is always a std::string type. Then at the end it does const string greet_write = tmpStringN; to assign the "sum" (concatenation, really) to your variable.

Does that answer your question?

thnx 4 reply,

btw, does that mean that if both std::string type would be validate? I mean at the the const string tmpString2 = tmpString1 + greeting;, does not both of them is string type?

Sorry, I'm not sure what your question is. The "+" operator for strings is defined as "an external function" (instance methods require that the implicit first parameter be the "this" pointer to the current object instance, but don't worry about that detail right now). Here's some code, with comments (see this for more details):

std::string hello = "Hello";  // this uses std::string operator= (const char *txt)
std::string world = " world";  // this also
std::string ex1 = hello + world;       // OK:  uses std::string & operator+ (const std::string & one, const std::string & two)
std::string ex2 = hello + " world";    // OK: uses std::string & operator+ (const st::string & one, const char * two)
std::string ex3 = "hello" + world;     // OK: uses std::string & operator+ (const char * one, const std::string & two)
std::string ex4 = "hello" + " world";  // ERROR: since the "+" is evaluated before the "=", it has no idea that what you're trying to create is a std::string, so it can't do anything intelligent at all

ha3, thnx 4 answer, I thought #3 is not possible, confused by the description from Accelerated C++

ty all...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.