Writing to text files or to the console in a C++ program? You might need to format some text data, and the C++ streams class includes some handy formatting features that allow you to do great things. Jeff Cogswell shows you how to use it to line up your text columns, right- or left-justify your text, and set the precision of your floating point numbers.
anyone who has had a CSC class with C++ gets this. I guess it is good for the 12 year old who wants to learn C++ but other than that, it is not to advanced.
Frankly, formatting text in C++ (and many other languages too) is a pain. The elegance of printf() comes from the readable separation of data and format – something which several other languages could learn from. (Prolog, Java (let’s hope 1.5 improves this), C++ (printf() is available, though), Pascal et.c.)
Yes, C printf is much better at formatting than the C++ iostreams, which are quite a pain to use. Some libraries also have quite nice sprintf variants, which allocate buffer by themselves and return result as some kind of string class.
But it is possible to have a reasonably usable formatting without separating the format from data – for example pascals write/writeln functions allow something like this:
writeln(‘Color: ‘, color: 14);
writeln(‘Count: ‘, count: 14);
writeln(‘Temperature:’, temp: 7: 2, ‘ C’);
which gives output like this:
Color:________green
Count:____________9
Temperature:__17.01 C
(used _ instead of spaces, since OSNews do not allow pre-tag)
http://boost.org
Yes, but unlike printf, iostreams are typesafe and you can add support for user-defined types.
But if you want something similar to printf, then try Compose: http://www.cs.auc.dk/~olau/compose/
or Boost format: http://www.boost.org/libs/format/doc/format.html
I don’t mind C++, but it’s streams are an absolute horrid mess. I’ll take printf and friends over that crap any day.
You know what. In all my years of programming in C/C++ I think I’ve had printf maybe bomb out once because of a bad type. Sorry, but I’ll take that risk and enjoy the terse elegance of printf over that sorry steaming pile of dung that is cout and friends.
…System.out.writeln. Java will finally get varags and a proper printf in 1.5 after, what 8 years? That is just pathetic.
Actually, I find Java’s approach pretty easy to learn. System.out.println() is a nice function to use… I believe C# has implemented something similar
It’s not that System.out.println() is not easy. It’s that it doesn’t have variable length args – well Java 1.5 does, but after what 8 years or so. In C# you can Console.WriteLine(“{0} {1} {2} {3}”, avar, bvar, cvar, dvar);
C# uses System.Console.WriteLine, like so:
string name = “Bob”;
System.Console.WriteLine(“Hi, my name is {0}”, name);
Personally, I like this better than printf, cuz you use numbers for placeholders instead of %d, %f, whatever.
My knowledge of C is sparse to say the least, but could you even do the above example using C & printf with a string variable? As I understand it, a string in C is just an array of chars?
I believe it is %c
but I am not sure because I have not done anything in C for a long time.
My knowledge of C is sparse to say the least, but could you even do the above example using C & printf with a string variable? As I understand it, a string in C is just an array of chars?
No, printf has no knowledge of the c++ string type.
char* name = “Bob”;
printf(“Hi, my name is %s
“, name);
My knowledge of C is sparse to say the least, but could you even do the above example using C & printf with a string variable? As I understand it, a string in C is just an array of chars?
No, printf has no knowledge of the c++ string type.
No, but you can always use string::c_str()
e.g.
string str = “Hello World!”;
printf(“%s”, str.c_str());
zzzzzz….
What a mess. Basically, it said: don’t do formatted stdout in C++.
Come on. iostreams is more than just cin or cout. You might not notice if all you ever coded in C++ were toy projects, but the times I was tempted to #include <cstdio> I can count on one hand.
You know what. In all my years of programming in C/C++ I think I’ve had printf maybe bomb out once because of a bad type. Sorry, but I’ll take that risk and enjoy the terse elegance of printf over that sorry steaming pile of dung that is cout and friends.
Ah, you mean the terse elegance of
fprintf(f, “%s %s %d %d
%s
%s”, employee.getName(), employee.getTitle(), employee.getAge(), employee.getSalary(), employee.getAddress());
versus the steaming pile of dung that is
cout << employee;
right?
python lets you do simple things like: print “hello” or then print x, “hello”, y or even print 3*”abc” … and then lets you do formatting if you wish like print “[%s] [%d]” %(str, int) … and if you like … print >> sys.stderr, “apple”
its good because its as simple as you need, or as complex as you need, without forcing you to grapple with syntax. how many times have you cried at printf when all you wanted to do was just output some denugging. and don’t forget the ”
” with printf!
Wrong
void PrintEmployee(Employee & e);
To me, overloading the << operator in an Employee class is just adding something to the class that shouldn’t be there in the first place.
if you want to use printf-style formating in your c++ stings use this function:
static std::string format(char *fmt, …)
{
char buff[100000];
va_list ap;
va_start(ap, fmt);
vsprintf(buff, fmt, ap);
va_end(ap);
return (char*)buff;
};
Heh, seems this is not an area I have ever really had issue with.
printf() would be awesome if it did type identification and formatting internally.
Seems that it should not be too hard with at least common types. Of course, question is how accurate one could be in type identification.
Oh well, I’ll just stick with my BString and printf(“%s
“, string.String());
That works pretty well 🙂 At least for most of my uses.
–The loon
Wrong
void PrintEmployee(Employee & e);
To me, overloading the << operator in an Employee class is just adding something to the class that shouldn’t be there in the first place.
You do know what you’re talking about, right?
You might want to take a look at the book “Effective C++” item 19: operator>> and operator<< are never member methods. They have to be global functions (like your PrintEmployee function). If they need access to private data of the class, they have to be declared as friend functions.
Why? Because otherwise you can write stuff like:
e >> cin;
e << cout;