Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iostream use of << to construct string

Tags:

c++

iostream

How can << be used to construct a string ala

int iCount;
char szB[128];
sprintf (szB,"%03i", iCount);
like image 519
Mike D Avatar asked Jan 30 '10 15:01

Mike D


People also ask

Does iostream contain string?

iostream includes string but including string explicitly is a good practice.

How do I convert a string to a Stringstream in C++?

To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.

Why do we use Stringstream in C++?

The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.


3 Answers

using namespace std;    
stringstream ss;
ss << setw(3) << setfill('0') << iCount;
string szB = ss.str();
like image 82
Peter Alexander Avatar answered Oct 05 '22 17:10

Peter Alexander


#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>

using namespace std;

int main() {
    int iCount = 42;
    ostringstream buf;
    buf << setw(3) << setfill('0') << iCount;
    string s = buf.str();
    cout << s;
}
like image 29
Sean Avatar answered Oct 05 '22 16:10

Sean


How can << be used to construct a string ala

This doesn't make any sense.

Use std::ostringstream in C++ if you want to do the similar thing.

 std::ostringstream s;
 int x=<some_value>;
 s<< std::setw(3) << std::setfill('0') <<x;
 std::string k=s.str();
like image 25
Prasoon Saurav Avatar answered Oct 05 '22 16:10

Prasoon Saurav