Hey all. Quickie question. Is there a way of doing the equivalent ofwith cin, where you read in the input and discard it?Code:scanf("%*s");
Hey all. Quickie question. Is there a way of doing the equivalent ofwith cin, where you read in the input and discard it?Code:scanf("%*s");
I assume that you mean read and discard input without creating a temporary variable. There's no easy way to do what you want, so you would just be better off creating that variable at some point, even if it's hidden behind a manipulator:
If you know how many characters you want to discard then you can use cin.ignore().Code:#include <iostream> #include <string> std::istream& discard ( std::istream& in ) { std::string temp; return in>> temp; } int main() { std::string word; for ( int i = 0; i < 3; i++ ) std::cin>> discard; std::cin>> word; std::cout<<"The fourth word is "<< word <<std::endl; }
My best code is written with the delete key.
Using a std::string as temp is overkill, though.
This ought to be faster, because it never allocates anything but stack memory.Code:#include <iostream> #include <locale> template<typename C, typename Traits = std::char_traits<C> > std::basic_istream<C, Traits> &discard(std::basic_istream<C, Traits> &in) { typedef std::ctype<C> mytype; C c; const mytype &ct = std::use_facet<mytype>(is.getloc()); while(in.get(c) && !ct.is(mytype::space, c)) { } return in; }
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law