Solved

String formatting in C++

Posted on 2006-11-21
2
189 Views
Last Modified: 2010-04-02
Hi Experts,

If I want to print something formatted in certain way in C,

printf("%s - %d - %s\n", str1, num, str2);


Is there C++ functions similar to printf for formatted output.  If so, how do I use it?
0
Comment
Question by:ambuli
  • 2
2 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 17988543
Just use 'cout' like

cout << str1 << " - " << num << " - " << str2 << endl;
0
 
LVL 86

Accepted Solution

by:
jkr earned 300 total points
ID: 17988557
BTW, the equivalent or 'sprintf()' would be a stringstream, e.g. instead of

sprintf(buf,"%s - %d - %s\n", str1, num, str2);
printf("%s",buf);

you'd use

#include <sstream>
using namespace std;

stringstream ss;

ss << str1 << " - " << num << " - " << str2 << endl;
cout << ss.str();
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
returning a dereferenced pts in C++ 10 158
Lambda for random numbers problem 7 119
sorting efficency of sorting algorithm 30 122
designing in object programming 12 95
Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question