XPost: alt.comp.lang.c++.misc
On 26.08.2024 21:45, Student Project wrote:
This is worth a try to run it in Linux, Windows and MacOS:
<*******************************************>
#include <iostream>
#include <string>
There are some minor issues with this program.
using namespace std;
Better not to get used to this bad habit.
int main()
{
string letters;
cout << "Enter a string to create a pyramid pattern: ";
// cin >> letters;
getline(cin, letters);
Error handling is missing. This call may fail for various reasons and
failure should be checked.
int len = letters.length();
int position = 0;
In real code the same type should be used for such variables as is used
by the interface functions (size_t instead of int, in this case), even
though it will make writing the later backward loop a bit more
cumbersome. Mixing types of different signedness and potentially of
different size is just another bad habit which should be avoided.
for (char c : letters)
{
int spaces = len - (position + 1);
while (spaces > 0)
{
cout << " ";
--spaces;
}
for (int i = 0; i < position; i++)
{
cout << letters.at(i);
The only reason to use at() instead of [] is to get a well-defined
exception if your program is buggy. Alas, exceptions are not caught nor
handled by this program, which makes it arguably more buggy, not less ;-)
}
cout << c;
for (int i = position - 1; i >= 0; i--)
{
cout << letters.at(i);
}
cout << "\n";
position++;
}
return 0;
}
<*******************************************>
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)