Thread: istream

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    100

    istream

    I have a method that needs to pass in an istream as a parameter:

    Code:
    int readRouteData(istream & inSource);
    istream has three subsets, correct? iostream, ifstream, istringstream

    Now i'm not clear on exactly what an istream is - "istream objects are stream objects used to read and interpret input from sequences of characters" - or how I would go about using one. Aren't cin/cout part of iostream? What is the point of passing in an istream to a method instead of retrieving the data beforehand and passing in the string instead? How would I go about declaring an istream variable?
    "I don't fail - I succeed at finding things that don't work"
    Website Promotion Techniques @AbstractPromotion.com

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You don't (necessarily) pass an istream to the function, you pass cin, or an ifstream, or an istringstream. The function takes an istream& as its parameter so that you can pass any of the three and it will work the same.

    The point of having it do that is so you can read in your data from a stream (likely in a text format) the same way whether you are reading from cin or from a file or from a string.

    If you only ever read in your data from cin, then you can still leave it as istream. Same if you only ever want to read from a file right now. The point is flexibility.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    100
    So when I called the function it might look like this?

    Code:
    readRouteData(cin);
    Usually I have data either coming from the keyboard or from a file, and I read it like this:

    Code:
    while(getline(cin, var))
    How would that implement into readRouteData? Just like I did above? And then inside of readRouteData my code would look like:

    Code:
    while(getline(inSource, var))
    ?
    "I don't fail - I succeed at finding things that don't work"
    Website Promotion Techniques @AbstractPromotion.com

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Yes and yes.

    If you wanted to, you could also call your function like this:
    Code:
    std::ifstream inFile("MyInputFile.txt");
    readRouteData(inFile);
    That's the flexibility part.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stupid compiler errors
    By ChrisEacrett in forum C++ Programming
    Replies: 9
    Last Post: 11-30-2003, 05:44 PM
  2. istream overload
    By Trauts in forum C++ Programming
    Replies: 6
    Last Post: 05-06-2003, 08:29 PM
  3. Replies: 5
    Last Post: 11-24-2002, 11:05 PM
  4. istream >> overloading
    By wazza13 in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2002, 10:56 PM
  5. <list>
    By Unregistered in forum C++ Programming
    Replies: 9
    Last Post: 02-24-2002, 04:07 PM