Thread: stringstream fun

  1. #1
    Registered User
    Join Date
    Jun 2011

    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...

    	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 {
    	} // End For
    	return pack;

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    United States
    Check your extraction.

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

    Then ask for a new string and try converting that one.

  3. #3
    Registered User
    Join Date
    Jun 2011
    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, 10: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, 05:56 AM