User Tools

Site Tools


cpp:stringstreams

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
cpp:stringstreams [2019/05/20 08:38] gthanoscpp:stringstreams [2019/05/21 06:27] – [String streams] gthanos
Line 5: Line 5:
   * **istringstream:** //stream// για διάβασμα από ένα //string/.   * **istringstream:** //stream// για διάβασμα από ένα //string/.
   * **ostringstream:** //stream// για γράψιμο σε ένα //string/.   * **ostringstream:** //stream// για γράψιμο σε ένα //string/.
-  * **stringstream:** //stream// για διάβασμα και γράψιμο σε ένα //string/.+  * **stringstream:** //stream// για διάβασμα και γράψιμο σε ένα //string//.
  
 <code cpp stringstream.cpp> <code cpp stringstream.cpp>
 #include <iostream> #include <iostream>
 +#include <sstream>
 +#include <string>
 +
 +using namespace std;
 int main() { int main() {
-  stream sstream;+  stringstream sstream;
      
   sstream << "Introducing C++ in CE325";   sstream << "Introducing C++ in CE325";
-  while( !sstream.str().empty() ) { +  string token; 
-    string token; +  while( sstream >> token ) { 
-    sstream >> token; +    cout << token << " ";
-    cout << token " ";+
   }   }
   cout << endl;   cout << endl;
 +  
 +  cout << "Stream contents: " << sstream.str() << endl;
 +  sstream.str("");
 +  cout << "Stream contents after clearing: " << sstream.str() << endl;
 } }
 </code> </code>
 +
 +<WRAP tip 80% center round>
 +Παρατηρήστε ότι καθώς διαβάζουμε το //stream// λέξη-λέξη το περιεχόμενο του //stream// παραμένει αμετάβλητο. Μπορείτε να 
 +  * Λάβετε το περιεχόμενο ενός //stringstream// χρησιμοποιώντας τη μέθοδο ''sstream.str();'' (χωρίς ορίσματα). 
 +  * καθαρίσετε το περιεχόμενο //stringstream// χρησιμοποιώντας τη μέθοδο ''sstream.str("");''.
 +</WRAP>
 +
 +===== Μετατροπή αριθμών σε strings και αντίστροφα =====
 +
 +Μπορούμε να χρησιμοποιήσουμε ένα //stringstream// προκειμένου να διαβάσουμε ή να γράψουμε ακέραιους ή αριθμούς κινητής υποδιαστολή από ένα string. Το παρακάτω παράδειγμα είναι αποκαλύπτικό:
 +
 +<code cpp stringstream.cpp>
 +#include <iostream>
 +#include <sstream>
 +#include <string>
 +
 +using namespace std;
 +
 +int main() {
 +  char cexpr[256];
 +  double opnd1, opnd2;
 +  char op;
 +  cout << "Enter arithmetic expression: ";
 +  cin.getline(cexpr, 256);
 +  istringstream sstream(cexpr);
 +  sstream >> opnd1 >> op >> opnd2;
 +  double result=0;
 +  switch(op) {
 +    case '+':
 +      result = opnd1 + opnd2;
 +      break;
 +    case '-':
 +      result = opnd1 - opnd2;
 +      break;
 +    case '*':
 +      result = opnd1 * opnd2;
 +      break;
 +    case '/':
 +      result = opnd1 / opnd2;
 +      break;
 +    default:
 +      cout << "ERROR\n";
 +      break;
 +  }
 +  cout << result << endl;
 +}
 +</code>
 +
 +
cpp/stringstreams.txt · Last modified: 2019/05/21 19:49 (external edit)