Sunday 15 February 2015

iostream - reading formatted input using C++ streams -


When using

stdio.h , I can easily sort some sort of formatted input Can read from: FILE * FIN = FOPAN (...); Fscanf (wings, "x =% d, y =% d", & amp; x, & y);

The great thing about this is that I really do not have to worry about how many places are between the letter 'x' and the low '=', and other small details

In C ++ it appears to me,

  ifstream fin (...); String s; Wings & gt; & Gt; S;   

The result of s can be "x" or "x =" or Based on the spacing of "X = 12" input.

What if scanf / fscanf iostream / fstream ?

using code> itemprop = "text">

This is really surprising, given a condition. I have these three functions which I do not touch anywhere in a header. These allow you to stream the letter literally, and I have never understood the string literals why they are not standard.

  #include & lt; Iostream & gt; // These are easy bits, which can be found in any template & lt; Class E, Class T, Int N & gt; Std :: basic_istream & lt; E, T & gt; & Amp; Operator & gt; & Gt; (Std :: basic_istream & lt; e, t & gt; and const e (& sliteral) [n]) {buffer [n -1] = {}; // in buffer & gt; & Gt; Buffer [0]; // Sleepy Spaces if (N> 2) in.read (buffer + 1, N -2); // read if left (strncmp (buffer, slitter, n-1)) // if it fails Insetstate (std :: ios :: failbit); // set in state return; } Template & lt; Class E, Class T & gt; Std :: basic_istream & lt; E, T & gt; & Amp; Operator & gt; & Gt; (Std :: basic_istream & lt; e, t & gt; and, cons E & amp; cliteral) {buffer (0); // in buffer & gt; & Gt; Buffer; // read data if (buffer! = Cliteral) // if it fails Insetstate (std :: ios :: failbit); // set in state return; } // Redirect unstable four arrays on their normal function template & lt; Class E, Class T, Int N & gt; Std :: basic_istream & lt; E, T & gt; & Amp; Operator & gt; & Gt; (Std :: basic_istream & lt; e, t & gt; and, e (& carray) [n]) {back std :: operator & gt; & Gt; (In, carre); }   

Looking at them, it is easy to relax:

  in & gt; & Gt; 'X' & gt; & Gt; '=' & Gt; & Gt; Data first & gt; & Gt; ',' & Gt; & Gt; 'Y' & gt; & Gt; '=' & Gt; & Gt; Data.second;   

For more complex situations, you might use std :: regex or boost :: regex , Or maybe a real laser / parser.

No comments:

Post a Comment