how would you use an if statement to test whether a variable is a hexadecimal? When I use the following code, it works if it is hex, but jumps into an infinite loop if it isn't. Also I want it to prompt the user for input again for iNum. Code (Text): do { if ( !(cin >> hex >> iNum)) // is iNum not hex? // loop else // don't loop }while(stuff here); Any help would be appreciated. Thanks.
Well, with what you are doing there, I am not entirely sure. Storing it as hex doesn't change anything I think, it just converts whatever the next byte is to a hexadecimal number and then stores it as decimal in iNum or something. You would still have to call it as << hex << before you do stuff with it, I think. There really isn't a specific hexadecimal datatype, so this can be pretty difficult.
cin>>hex>>iNum doesn't quite do that. cin>>hex will just read characters until the first invalid character, then return the number, or 0 if no valid number, into iNum, then returning the cin object. You want to check to see if a number is completely hex? You will need to read the number in as a string: Code (Text): string s; cin >> s; // if one word getline(s, cin); // if a whole line Then you want to check s to see if it is a hex number by checking the characters. I'll leave that up to you.
To check if you input is a valid hex value, use: Code (Text): bool IsAllHex (char* must_be_hex) { char copy_of_param[64]; return (strtok(strcpy(copy_of_param, must_be_hex), "0123456789ABCDEFabcdef") == NULL); } To convert a string to a C-style char* string, use c_str(), for example: string stringName = "hello"; char cString[64] = stringName.c_str();
You can't do that. You have to strcpy the output of c_str(). Or you can Code (Text): const char *cString = stringName.c_str(); but of course you can't modify that. I see Alrightyman already has his solution though.