Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the C++ equivalent of sprintf?
The sprintf() function of C library equivalent to C++ that is used to create strings with a specified format like custom text with numbers or names. In C++, we can perform the same operation as in C with the help of ostringstream.
C++ std::ostringstream
The ostringstream is known for the output string stream and is defined under <sstream> header file. This is used to build the string by writing some text into it.
Syntax
i. Following is the basic syntax of sprint() function in C:
int sprintf(char *str, const char *format, ...);
ii. Here, we show the syntax of C++ function which has similar function w.r.t sprintf():
ostringstream os;
Example of C++ Equivalent to sprint() Function
In this program, we shows how ostringstream of C++ works similar to the sprintf() of C. Here, we write one program line as os << "This is a string... which demonstrates how to add text and numbers into the stream.
#include<iostream>
#include<sstream>
using namespace std;
int main() {
string my_str;
// os is just name of the variable
ostringstream os;
os << "This is a string where we will store the value of " << 50 << " and also store the value as " << 52.32 ;
// convert stream to my_str string
my_str = os.str();
cout << my_str;
return 0;
}
The above code produces the following output:
This is a string where we will store the value of 50 and also store the value as 52.32