问题
I am looking into code at work. I am having following code. In following code what is the meaning of the last statement?
bOptMask = true;
std::string strMask;
strMask.append(optarg);
std::stringstream(strMask) >> std::hex >> iMask >> std::dec;
In addition to the above question: I have string input and I need to know how to convert it to an integer using C++ streams as above instead of atoi()
.
The problem I am facing is if I give input
strOutput.append(optarg);
cout << "Received option for optarg is " << optarg << endl;
std::stringstream(strOutput) >> m_ivalue ;
cout << "Received option for value is " << m_ivalue << endl;
For the above code, if I am running with argument "a" I am having an output with first line as "a" and a second line output as 0. I am not sure why, can any one explain?
回答1:
The last statement creates a temporary stringstream and then uses it to parse the string as hexadecimal format into iMask.
There are flaws with it though, as there is no way to check that the streaming succeeded, and the last stream achieves nothing as you are dealing with a temporary.
Better would be to create the stringstream as a non-temporary, ideally using istringstream as you are only using it to parse string to int, and then checking whether the conversion succeeds.
std::istringstream iss( strMask );
iss >> std::hex;
if(!( iss >> iMask ))
{
// handle the error
}
You only need to set the mode back to decimal if your stringstream is now about to parse a decimal integer. If it is going to parse more hex ones you can just read those in too, eg if you have a bunch of them from a file.
How you handle errors is up to you.
std::hex
and std::dec
are part of the <iomanip>
part of streams that indicate the way text should be formatted. hex means "hexadecimal" and dec means "decimal". The default is to use decimal for integers and hexadecimal for pointers. For reasons unknown to me there is no such thing as a hex representation for printing float or double, i.e. no "hexadecimal point" although C99 sort-of supports it.
回答2:
The code takes the string optarg
and, treating it as hex, converts it to an integer and stores it in iMask.
If you remove the std::hex modifier you can parse the input as decimal. However, I usually use boost's lexical_cast for this. For example:
int iMask = boost::lexical_cast< int >( strMask );
回答3:
This code uses manipulators to set the stream to expect integers to be read in base 16 (hexadecimal, using the digits 0123456789ABCDEF), then extracts a hexadecimal number from the string, storing it in iMask, and uses another manipulator to set the string stream back to the default of expecting integers to be written in decimal form.
来源:https://stackoverflow.com/questions/5117844/c-stringstreams-with-stdhex