User Tools

Site Tools


cpp:stream_states

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:stream_states [2019/05/21 07:01]
gthanos
cpp:stream_states [2019/05/21 07:39]
gthanos
Line 18: Line 18:
  
 <code cpp check_file_open.cpp> <code cpp check_file_open.cpp>
-// getting the state of stream objects 
 #include <iostream> #include <iostream>
 #include <fstream> #include <fstream>
 +
 +using namespace std;
  
 int main () { int main () {
-  std::fstream fs; +  std::ifstream fs; 
-  fs.open ("hello.txt");+  fs.open("non-exist.txt");
   if ( (fs.rdstate() & std::fstream::failbit ) != 0 )   if ( (fs.rdstate() & std::fstream::failbit ) != 0 )
-    std::cerr << "Error opening file 'hello.txt'\n"+    std::cerr << "Error opening file 'non-exist.txt'\n";
-  return;+
 } }
 </code> </code>
 +
 +===== Έλεγχος των τιμών εισόδου (input validation) =====
 +
 +Με έλεγχο των παραπάνω //flags// μπορούμε να κάνουμε έλεγχο της εισόδου που εισάγει ο χρήστης σε ένα πρόγραμμα, όταν καλούμαστε να διαβάσουμε έναν ακέραιο ή αριθμό κινητής υποδιαστολής. Δείτε το παρακάτω παράδειγμα, όπου ο χρήστης καλείτε να εισάγει το βάρος του ως θετικό αριθμό κινητής υποδιαστολής. Εάν εισάγει κάτι διαφορετικό το πρόγραμμα ελέγχει το //failbit// και εφόσον αυτό είναι ενεργό, επεναλαμβάνει τη διαδικασία. Η συνάρτηση [[http://www.cplusplus.com/reference/istream/istream/ignore/|ignore]] αγνοεί τόσους χαρακτήρες όσους προσδιορίζει η 1η παράμετρος ή εάν βρεθεί ο χαρακτήρας που προσδιορίζεται στη 2η παράμετρο (όποιο από τα δύο συμβεί 1ο). 
 +
 +<code cpp input_validation.cpp>
 +#include <iostream>
 +#include <fstream>
 +
 +using namespace std;
 +
 +int main() {
 +  double weight;
 + 
 +  while (true) {
 +    cout << "Enter your weight: ";
 +    cin >> weight;
 + 
 +    if (cin.fail()) {
 +      // We failed to extract a double
 +      cin.clear();           // reset stream state to goodbit.
 +      cin.ignore(256, '\n'); // remove any input from the stream until \n
 +      continue;
 +    }
 + 
 +    if (weight <= 0)
 +      continue;
 + 
 +    break;
 +  }
 + 
 +  cout << "You weight is: " << weight << endl;
 +}
 +</code>
 +
 +
cpp/stream_states.txt · Last modified: 2021/06/01 06:55 (external edit)