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
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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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 }
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.