Reading and throwing away input

This is a discussion on Reading and throwing away input within the C++ Programming forums, part of the General Programming Boards category; Hey all. Quickie question. Is there a way of doing the equivalent of Code: scanf("%*s"); with cin, where you read ...

  1. #1
    Ink
    Ink is offline
    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,796
    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,893
    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, 12:57 PM
  2. Throwing exceptions with constructors
    By nickname_changed in forum C++ Programming
    Replies: 14
    Last Post: 07-08-2003, 10:21 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21