stringstream fun

This is a discussion on stringstream fun within the C++ Programming forums, part of the General Programming Boards category; Hey everybody... I am taking a string full of hex values and putting them into an array of unsigned shorts. ...

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    17

    stringstream fun

    Hey everybody...

    I am taking a string full of hex values and putting them into an array of unsigned shorts. However I want to be able to check to see if the value is actually a hex value (IE input foo would return error). Right now if there is an invalid point it just sits on itself and reads the same value over and over again because it can't read that string since it is not a hex...
    So basically I need it to check to make sure the value is indeed actually hex, or it won't even read it in. What is the best way to do this? I thought of reading in the value as a string first, then reading that into a hex value and see if it takes, but that seems excessive...

    Code:
    	int value, i;
    	unsigned short *pack = new unsigned short [ count+5 ]; 
    	stringstream dataStream ( data );
    
                // Arr spots 0-2 held for other purposes
    
                for ( i = 3; i < cmd.count+4; i++) {
    		dataStream >> hex >> value; 
    		// Check validity of the value
    		if ( value > MAX_DATA_VALUE || value < 0  ) {
    			cout << "ERR: Data value " << hex << value << " is out of range" << endl;
    			pack[0] = INVALID_VALUE;
    			return pack;
    		}
    		else {
    			pack[i]=value;	
    		}
    	} // End For
    	return pack;
    Thanks!

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,622
    Check your extraction.

    Code:
     if ( !(dataStream >> hex >> value) )
    If the stream can't do the conversion then, you know it's wrong. You empty the stream then:

    Code:
     dataStream.str("");
    Then ask for a new string and try converting that one.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    17
    Sweet that works well, thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stringstream help
    By Airick92 in forum C++ Programming
    Replies: 6
    Last Post: 04-02-2011, 10:28 AM
  2. stringstream Help...
    By neogst in forum C++ Programming
    Replies: 4
    Last Post: 02-08-2011, 09:23 AM
  3. Stringstream
    By lruc in forum C Programming
    Replies: 9
    Last Post: 03-23-2009, 02:27 PM
  4. stringstream
    By jk1998 in forum C++ Programming
    Replies: 2
    Last Post: 07-27-2007, 06:35 PM
  5. std::stringstream
    By Magos in forum C++ Programming
    Replies: 2
    Last Post: 11-13-2004, 04:56 AM

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