cpp:stringstreams
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
cpp:stringstreams [2019/05/20 08:22] – created gthanos | cpp:stringstreams [Unknown date] (current) – external edit (Unknown date) 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
====== String streams ====== | ====== String streams ====== | ||
- | Εκτός από τις κλάσεις για ανάγνωση ή εγγραφή από αρχείο ή τα //stdin// και //stdout// η // | + | Εκτός από τις κλάσεις για ανάγνωση ή εγγραφή από αρχείο ή τα //stdin// και //stdout// η // |
+ | |||
+ | * **istringstream: | ||
+ | * **ostringstream: | ||
+ | * **stringstream: | ||
+ | |||
+ | <code cpp stringstream.cpp> | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | using namespace std; | ||
+ | int main() { | ||
+ | stringstream sstream; | ||
+ | |||
+ | sstream << " | ||
+ | string token; | ||
+ | while( sstream >> token ) { | ||
+ | cout << token << " "; | ||
+ | } | ||
+ | cout << endl; | ||
+ | |||
+ | cout << " | ||
+ | sstream.str("" | ||
+ | cout << " | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <WRAP tip 80% center round> | ||
+ | Παρατηρήστε ότι καθώς διαβάζουμε το //stream// λέξη-λέξη το περιεχόμενο του //stream// παραμένει αμετάβλητο. Μπορείτε να | ||
+ | * Λάβετε το περιεχόμενο ενός // | ||
+ | * καθαρίσετε το περιεχόμενο // | ||
+ | </ | ||
+ | |||
+ | ===== Μετατροπή αριθμών σε strings και αντίστροφα ===== | ||
+ | |||
+ | Μπορούμε να χρησιμοποιήσουμε ένα // | ||
+ | |||
+ | <code cpp stringstream.cpp> | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | using namespace std; | ||
+ | |||
+ | int main() { | ||
+ | char cexpr[256]; | ||
+ | double opnd1, opnd2; | ||
+ | char op; | ||
+ | cout << "Enter arithmetic expression: "; | ||
+ | cin.getline(cexpr, | ||
+ | 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 << " | ||
+ | break; | ||
+ | } | ||
+ | cout << result << endl; | ||
+ | } | ||
+ | </ | ||
+ |
cpp/stringstreams.1558340537.txt.gz · Last modified: 2019/05/20 07:22 (external edit)