Hello,
Is it possible to tell cout that from now on, all output must be indented with n spaces?
For example:
cout << "blahblah" << indent(3) << endl;
cout << "abc" << endl;
cout << "123" << endl;
would output:
Code:blahblah
abc
123
Printable View
Hello,
Is it possible to tell cout that from now on, all output must be indented with n spaces?
For example:
cout << "blahblah" << indent(3) << endl;
cout << "abc" << endl;
cout << "123" << endl;
would output:
Code:blahblah
abc
123
Not that I'm aware of.
You could have an object that generates a suitably indented string, e.g:
--Code:class Indent
{
private:
unsigned int level;
public:
Indent(int n = 0): level(n) {}
~Indent() {};
void setLevel(int n) { level = n; };
operator std:string()
{
return std::string(level, ' ');
}
};
int main()
{
Indent ind;
std::cout << ind << "Hello, world" << std::endl;
ind.setLevel(3);
std::cout << ind << "abc" << std::endl;
std::cout << ind << "123" << std::endl;
return 0;
}
Mats
Thanks mats, but I need a method where the output producing code is unaware of the indents. I guess that's not possible.
How about replacing endl with a string? This could contain only '\n' or '\n' followed by a number of spaces.
Code:#include <iostream>
#include <string>
int main()
{
std::string newline("\n");
std::string newline_plus_spaces = newline + std::string(3, ' ');
std::string end_line = newline_plus_spaces;
std::cout << "Hello, world" << end_line; //next line is indented
std::cout << "abc" << end_line; //same
end_line = newline;
std::cout << "123" << end_line; //next line is not indented
}