News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ Tips: IO - sscanf equivalent using streams

Started by ben2ong2, October 06, 2006, 11:20:17 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

(Newsgroups: comp.lang.c++.moderated, 9 Sep 96)


PROBLEM: "Daniel J. Levine" <einstein@f2ahp20.jhuapl.edu>

I like using streams with C++, but I have not seen any examples
which explain how to do the following with streams:

[...]

int count = sscanf(buffer, "x=%d y=%d", &x, &y);


RESPONSE: Jim Weirich <jim@lexis-nexis.com>

There is no built-in option for skipping the "x=" portion of the
input.  But it is fairly simple to come up with a work-around.  The
code given below allows a syntax like ...

    bufferStream >> Eat("x=") >> x >> Eat("y=") >> y;

The approach is quite general and I've used it for specialized output
formatting, but this is the first I've used it for input.

--><--snip--><--------------------------------------------------------

#include <iostream.h>
#include <strstream.h>
#include <string.h>

class Eat {
public:
    Eat (const char *);      // eat until string
    ~Eat ();
    friend istream& operator>> (istream&, Eat&);
private:
    char * myString;
};

Eat::Eat (const char * s)
{
    myString = new char[strlen(s)+1];
    strcpy (myString, s);
}

Eat::~Eat ()
{
    delete [] myString;
}

istream& operator>> (istream& is, Eat& e)
{
    int n = 0;
    int len = strlen(e.myString);
    while (n < len && is) {
   char ch;
   is.get(ch);
   if (ch == e.myString[n]) {
       n++;
   } else {
       n = 0;
   }
    }
    return is;
}

main ()
{
    int x, y;
    istrstream ss ("x=123 y=246");

    ss >> Eat("x=") >> x >> Eat("y=") >> y;

    cout << "x is " << x << endl;
    cout << "y is " << y << endl;

    return 0;
}

--><--snip--><--------------------------------------------------------
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login