#include "stdafx.h"
#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 << "What's your name? ";
	
	// read the name
	string name;
	cin >> name;
	
	// build the message that we intend to write
	const string greeting = "Hello, " + name + "! Nice to meet you!";
	
	// 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;
}

Whats wrong with this code? It keeps looping while it shouldn't. Don't know whats the problem. It debugs fine.

Thanks in advance

Recommended Answers

All 3 Replies

It's stuck here:

if(r==0 || r==rows-1 || c==0 || c==cols-1)
{
cout << "*";  //you need a ++c here!
}

And your code would look better if you use else if() {} else{} instead of else {if() {} else{}} !

So all I need is a ++c there?

Apparently yes.

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.