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 revision Previous revision
Next revision
Previous revision
Next revision Both sides next revision
cpp:stringstreams [2019/05/20 08:39]
gthanos
cpp:stringstreams [2019/05/20 11:42]
gthanos [String streams]
Line 9: Line 9:
 <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>
 +
 +<WRAP tip 80% center round>
 +Παρατηρήστε ότι καθώς διαβάζουμε το //stream// λέξη-λέξη το περιεχόμενο του //stream// παραμένει αμετάβλητο. Μπορείτε να καθαρίσετε το περιεχόμενο //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> </code>
 +
 +
cpp/stringstreams.txt · Last modified: 2019/05/21 19:49 (external edit)