C++ Tutorial/File Stream/stringstream — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
м (1 версия: Импорт контента...)
 
(нет различий)

Текущая версия на 13:31, 25 мая 2010

Demonstrate string streams

<source lang="cpp">#include <iostream>

  1. include <sstream>

using namespace std;

int main() {

 stringstream s("This is initial string."); 

 // get string 
 string str = s.str(); 
 cout << str << endl; 

 // output to string stream  
 s << "Numbers: " << 10 << " " << 123.2; 

 int i; 
 double d; 
 s >> str >> i >> d; 
 cout << str << " " << i << " " << d; 

 return 0; 

}</source>

This is initial string.
Numbers: 10 123.2

stringstream::str( empty string): Empty the string

<source lang="cpp">#include <iostream>

  1. include <iomanip>
  2. include <string>
  3. include <sstream>

using namespace std; int main( ) {

 stringstream ss;
 ss << "string " << 9 << 1.2;
 cout << ss.str( ) << endl;
 ss.str("");                  // Empty the string
 cout << ss.str( ) << endl;

}</source>

string 91.2

stringstream::str( ) returns a string

<source lang="cpp">#include <iostream>

  1. include <iomanip>
  2. include <string>
  3. include <sstream>

using namespace std; int main( ) {

 stringstream ss;
 ss << "string " << 9 << 1.2;
 cout << ss.str( ) << endl;   // stringstream::str( ) returns a string

}</source>

string 91.2

Use stringstream to parse a number

<source lang="cpp">#include <iostream>

  1. include <sstream>
  2. include <string>

using namespace std; double parse(const string& str) {

 stringstream ss(str);
 double d = 0;
 ss >> d;
 if (ss.fail( )) {
   throw (str +" is not a number");
 }
 return (d);

} int main( ) {

 try {
   cout << parse("1.234e5") << endl;
   cout << parse("6.02e-2") << endl;
   cout << parse("asdf") << endl;
 }
 catch (string& e) {
   cerr << e << endl;
 }

}</source>

123400
0.0602
asdf is not a number