Can cout do like printf("Name: %s, Age: %d\n",name,age)?

C

cylin

Dear all,

To do below is too long.
cout << "Name: " << name << ", Age: " << age << endl;
Can cout use "%" to implement?
Thanks.

cylin.
 
S

Sam Holden

Dear all,

To do below is too long.
cout << "Name: " << name << ", Age: " << age << endl;

If 20 characters of typing is enough to make you want to avoid
type safety, then I don't C++ is the language for you. :)
Can cout use "%" to implement?

No.
 
P

Peter van Merkerk

To do below is too long.
cout << "Name: " << name << ", Age: " << age << endl;

Why it is too long?
If you would remove the spaces around the '<<' operators (just like the
printf), the cout version is only 4 character longer. That seems to be a
small price to pay for the type safety you get with cout.
Can cout use "%" to implement?

No.
 
B

Bob Jacobs

cylin said:
Dear all,

To do below is too long.
cout << "Name: " << name << ", Age: " << age << endl;
Can cout use "%" to implement?
Thanks.

Your two examples are not equivalent. In the version using cout you flush
the output stream, whereas in the printf version you don't.
 
M

Mike Wahler

cylin said:
Dear all,

To do below is too long.
cout << "Name: " << name << ", Age: " << age << endl;

Removing unnecessary whitepace and using
same newline expression in order to form
a valid comparision:

printf("Name: %s, Age: %d\n",name,age);

cout<<"Name: "<<name<<", Age: "<<age<<'\n';

Is an extra four characters really too high
a price to pay for type safety?
Can cout use "%" to implement?

I suppose one could write some code to simulate
it, but what's the point?

Also note that 'printf()' is just as valid
(but less safe) a function in C++ as are the
stream inserters.

If you insist upon using '%' specifiers, why not just
use 'printf()'?

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top