TITLE: sscanf equivalent using streams (Newsgroups: comp.lang.c++.moderated, 9 Sep 96) PROBLEM: "Daniel J. Levine" 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 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 #include #include 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--><--------------------------------------------------------