Initializing an istringstream

This is a discussion on Initializing an istringstream within the C++ Programming forums, part of the General Programming Boards category; I have a string object and an istringstream object and I was wondering if it was possible to set the ...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    271

    Initializing an istringstream

    I have a string object and an istringstream object and I was wondering if it was possible to set the string data in the stringstream using a member function.

    I know you can initialize an istringstream like this:
    Code:
    istringstream somestream(somestring);
    But I wasn't able to find a straightforward way to recycle the stringstream with a member function. The only way I was able to think of was:
    Code:
    	istringstream* somestream;
    	somestream = new istringstream(somestring);
    	
    	//do something with the stream
    
    	delete somestream;
    	somestream = new istringstream(someotherstring);
    	
    	//do something else with the stream
    	
    	delete somestream;
    It works, but I have a feeling there's a better way to do it. But how?

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,068
    There is a str() member function available for both istringstreams and ostringstreams. EDIT: Sorry, I'll clarify better, this can be used in conjunction with the inherited clear() function.
    Code:
    #include <iostream>
    #include <sstream>
    
    int main() {
        std::istringstream inStr;
        float PI, E;
        
        inStr.str("3.14"); 
        inStr >> PI;
        
        inStr.clear(); 
        inStr.str("2.71"); 
        inStr >> E;
        
        std::cout << PI << std::endl << E;
        
        return 0;
    }
    You have to clear the stream because after you read in the whole thing, the eof-flag is set to true.
    Last edited by SlyMaelstrom; 05-11-2006 at 08:47 PM.
    Sent from my iPad®

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    271
    Thank you. That worked wonderfully.

    May your milk forever flow like the galaxy from the udders of cows.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Testing some code, lots of errors...
    By Sparrowhawk in forum C Programming
    Replies: 48
    Last Post: 12-15-2008, 03:09 AM
  2. istringstream problem in switch block?
    By wolfindark in forum C++ Programming
    Replies: 4
    Last Post: 06-24-2007, 11:56 PM
  3. Replies: 1
    Last Post: 10-27-2006, 01:21 PM
  4. confused with istringstream
    By terracota in forum C++ Programming
    Replies: 4
    Last Post: 07-23-2004, 10:49 PM
  5. Initializing and Solving matrices
    By scottmanc in forum C++ Programming
    Replies: 1
    Last Post: 11-16-2003, 03:06 PM

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