Suppose I have a string with hex numbers in it like this "1a:2b:3c:4d:5e:6f"
How do I use istringstream to parse it to get each of 1a, 2b, 3d, 4d, 5e, 6f hex numbers ?
cheers
Suppose I have a string with hex numbers in it like this "1a:2b:3c:4d:5e:6f"
How do I use istringstream to parse it to get each of 1a, 2b, 3d, 4d, 5e, 6f hex numbers ?
cheers
Like this, (you may have to change the condition of the looping)
Code:while(your_stream) { your_stream >> std::hex >>your_int; char temp; your_stream >> temp; }
So I'd do something like:
Code:istringstream iss (mystring,istringstream::in); int hexval[6]; int temp; for (n=0; n<6; n++) { iss >> std::hex >> hexval[n]; iss >> temp }
Not quite. A colon cannot be read as an int, and it won't be skipped if it is there. Each attempt to read an int after encountering the first colon will fail.
A colon can be read (and skipped) as a char though. That is why temp, in manasij7479's example, was of type char, not int.
this worked but i wanted hexvalue to be unsigned char, this didn't work - none of the values written to it were correct
this doesn't work:
value written to val[n] is always wrong if val array is unsigned charCode:int main(int argc, char* argv[]) { int n; string stringvalues; //int val[6]; unsigned char val[6]; char temp; stringvalues = "1a:2b:3c:4d:5e:6f"; istringstream iss (stringvalues,istringstream::in); for (n=0; n<6; n++) { iss >> std::hex >> (unsigned char) val[n]; iss >> temp ; } return 0; }
Get the number inputs as integers.
After that type cast them into unsigned chars when putting into the unsigned char array.
Your code does not work because the stream enters into an error state when it attempts to read in a number into a char.
What?? A char is a number. The stream will not go into an error state by trying to put a number into a char/unsigned char.Your code does not work because the stream enters into an error state when it attempts to read in a number into a char.
The problem is trying to use an unsigned char in the extraction operation. You need to extract each section into an int, then convert to the unsigned char.
JimCode:#include <iostream> #include <string> #include <sstream> using namespace std; int main(int argc, char* argv[]) { int n; string stringvalues; unsigned char val[6]; int int_temp; char temp; stringvalues = "1a:2b:3c:4d:5e:6f"; istringstream iss (stringvalues); for(int i = 0; i < 6; ++i) { iss >> std::hex >> int_temp; // Extract the number into an int. val[i] = int_temp; // Convert the int to your unsigned char. iss >> temp; // Extract and throw away the colon. } for(int i = 0; i < 6; ++i) cout << static_cast<int>(val[i]) << " "; return 0; }