istream and variable types using template

I'm using istream to get 'general' input from the user (maybe from a file, from keyboard, etc.) using a template.

template<typename T>
void ClassName<T>::SomeFunction { //forgot to put this line in, might've caused confusion
istream input;
T thing;

while (input >> thing)
{
// do stuff in here
// an array of type T will contain thing
}

}

I only want to record int and double types (which T can handle) but if it sees any other type (like a string or a char) then it will stop.

So far it crashes when I enter a letter. Is there a way to "stop" or "exit" the input stream when it sees a string or letter?
Last edited on
Your code doesn't make total sense. Are you wanting to read either a sequence of ints or a sequence of doubles?

I want to read in either a bunch of int or a bunch of double, which is why I'm using a template. The problem is that I don't know how to stop the input stream if a suddenly different type comes in or end of file.
You need a smarter read loop. You will have to test whether it has entered as error state, etc (see http://www.cplusplus.com/reference/iostream/ios/bad/) and handle those conditions gracefully.

Topic archived. No new replies allowed.