What is the C++ equivalent of sprintf?


The sprint() function is present inside the C and C++ also. This function is used to store something inside a string. The syntax is like the printf() function, the only difference is, we have to specify the string into it.

In C++ also, we can do the same by using ostringstream. This ostringstream is basically the output string stream. This is present in the sstrem header file. Let us see how to use this.

Example

#include<iostream>
#include<sstream>
using namespace std;
int main() {
   string my_str;
   ostringstream os;
   os << "This is a string. We will store " << 50 << " in it. We can store " << 52.32 << " also.";
   my_str = os.str(); //now convert stream to my_str string
   cout << my_str;
}

Output

This is a string. We will store 50 in it. We can store 52.32 also.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements