C++/File/ostrstream

Материал из C\C++ эксперт
Перейти к: навигация, поиск

construct a table of circular areas

<source lang="cpp">

  1. include <iostream>
  2. include <sstream>
  3. include <locale>
  4. include <iomanip>

using namespace std; int main() {

 locale usloc("English_US");
 ostringstream ostr;
 // Give a new, empty string to ostr.
 ostr.str(string());
 // construct a table of circular areas.
 ostr << setprecision(4) << showpoint << fixed << left;
 ostr << "Diameter    Area\n";
 cout << "A table of circular areas.\n";
 for(int i=1; i < 10; ++i)
   ostr << left << "   " << setw(6) << i << setw(8) << right << i*3.1416 << endl;
 cout << ostr.str();
 return 0;

}


 </source>


Display the contents of strin via calls to get()

<source lang="cpp">

  1. include <iostream>
  2. include <sstream>

using namespace std; int main() {

 char ch;
 ostringstream strout;
 strout << 10 << " " << -20 << " " << 30.2 << "\n";
 strout << "This is a test.";
 cout << strout.str() << endl;
 strout << "\nThis is some more output.\n";
 cout << "Use an input string stream called strin.\n";
 // use the contents of strout to create strin:
 istringstream strin(strout.str());
 // Display the contents of strin via calls to get().
 cout << "Here are the current contents of strin via get():\n";
 do {
   ch = strin.get();
   if(!strin.eof()) cout << ch;
 } while(!strin.eof());

}


 </source>


Freeze dynamic buffer and return pointer to it

<source lang="cpp">

  1. include <strstream>
  2. include <iostream>

using namespace std; main() {

 char *p;   
    
 ostrstream outs;  
    
 outs << "I like C++ ";   
 outs.setf(ios::showbase);   
 outs << 100 << ends;   
    
 p = outs.str();
    
 cout << p;   
    
 delete p;  
 return 0;   

}


 </source>


use the contents of strout to create strin

<source lang="cpp">

  1. include <iostream>
  2. include <sstream>

using namespace std; int main() {

 char ch;
 ostringstream strout;
 strout << 10 << " " << -20 << " " << 30.2 << "\n";
 strout << "This is a test.";
 cout << strout.str() << endl;
 strout << "\nThis is some more output.\n";
 istringstream strin(strout.str());
 do {
   ch = strin.get();
   if(!strin.eof()) cout << ch;
 } while(!strin.eof());
 cout << endl;

}


 </source>