Thread: Reading and throwing away input

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    4

    Reading and throwing away input

    Hey all. Quickie question. Is there a way of doing the equivalent of
    Code:
    scanf("%*s");
    with cin, where you read in the input and discard it?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    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:
    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;
    }
    If you know how many characters you want to discard then you can use cin.ignore().
    My best code is written with the delete key.

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Using a std::string as temp is overkill, though.
    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;
    }
    This ought to be faster, because it never allocates anything but stack memory.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. throwing away spaces and \n
    By kippwinger in forum C++ Programming
    Replies: 6
    Last Post: 07-21-2003, 11:57 AM
  2. Throwing exceptions with constructors
    By nickname_changed in forum C++ Programming
    Replies: 14
    Last Post: 07-08-2003, 09:21 AM