Why does the emission of braces in the following infamous example produce the desired greeting output? However, when adding braces on row 37 & 40 under the else, for the two statements, an infinite loop is produced? The first code example produces an infinite loop of asterisks. The second produces the desired output of a returned bordered greeting.
#include<iostream>
#include<string>
using std::cin; using std::string;
using std::cout; using std::endl;
int main()
{
cout << "Please enter your first Name: ";
string name;
cin >> name;
const string greeting = "Hello, " + name + "!";
const int pad = 1;
const int rows = pad*2 + 3;
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();
}
else
{
if(r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
{
cout << "*";
}
else
{
cout << " ";
++c;
}
}
}
cout << endl;
}
return 0;
}
/*Example 2*/
#include<iostream>
#include<string>
using std::cin; using std::string;
using std::cout; using std::endl;
int main()
{
cout << "Please enter your first Name: ";
string name;
cin >> name;
const string greeting = "Hello, " + name + "!";
const int pad = 1;
const int rows = pad*2 + 3;
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();
}
else
{
if(r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
cout << "*";
else
cout << " ";
++c;
}
}
cout << endl;
}
return 0;
}