First of all, don't build a habit of using using namespace std
std::endl
will put a linebreak, but it will also flush your stream. Put easily, outputting something is a really costly (=takes a long time) action in regard to other actions. To account for this, streams are buffered and once the buffer is full it will be flushed automatically. When you use std::endl
the buffer might be flushed prematurely and this will tank performance. This is of course not really an issue in this small exercise, but I think it's still good to know. You can use \n
instead. Although it might not look like it, it will provide a platform independend linebreak and should virtually always be used instead of std::endl
.
Then consider what your function loop
should do. Right now, you said it has return type char
but it's not returning something. Therefore you should correct this and specify that this function is not returning anything, but just performing an action, hence return type void
.
As suggested by John Zwinck, if you pass the stream as an argument, your function becomes more powerful and works with any kind of outgoing stream (i.e. std::ostream
).
We can make the function even more generic, but I'll leave it to you to understand the code (if not, feel free to post a comment for clarification). Please note also, that loop
is not a descriptive name. I have no idea what loop
does. Always give your functions a name that makes it clear what they are doing.
#include <iostream>
#include <fstream>
void print_letter_triangle(std::ostream& out, char c = 'a', int count = 15)
{
for( int i = 0; i < count; i++ ){
for( int j = 0; j < i; j++ )
{
out << c;
}
out << '\n';
}
}
int main()
{
// for testing purposes
print_letter_triangle(std::cout);
print_letter_triangle(std::cout, 'b');
print_letter_triangle(std::cout, 'c', 7);
std::ofstream week2("week2assignment.txt");
if( week2.is_open() )
{
print_letter_triangle(week2);
week2.close();
}
else
{
std::cout << "Error: File wasn't created.\n";
}
return 0;
}
Lastly: Try to build an early habit of how you want to format your code, positions of curly braces, spaces around operators. Right now it was a little bit inconsistent (which might as well have been caused by putting it on StackOverflow).
There are a couple more nitpicks one can offer (for example, I changed the loop to start from 0
and used the <
instead of the <=
operator, you can convince yourself that this does not change the number of loop iterations. However, it is common in programming languages to start from 0
(as counter-intuitive as that might be at first). Finally, since negative counting values do not make sense in this loop, one might change int
to unsigned int
, but I felt that might have been a little too much. Feel free to do so on your own, if you wish).