C ++ stringstreams with std :: hex

I study the code at work. I have the following code. In the 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 question above: I have a string input, and I need to know how to convert it to an integer using C ++ streams as above, not 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 run the argument “a”, I have output with the first line as “a” and the second output of the line is 0. I don't know why, can anyone explain?

+4
source share
3 answers

The last statement creates a temporary stringstream and then uses it to parse the string as a hexadecimal format in iMask.

There are flaws with it, although there is no way to verify that the streaming was successful, and the last stream does not achieve anything, since you are dealing with a temporary one.

It would be better to create a stringstream as non-temporary, ideally using istringstream, since you only use it to parse the string for int, and then to verify that the conversion completed successfully.

 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 will now parse the decimal integer. If it parses more than hexadecimal, you can just read them too, for example, if you have a bunch of files.

How you handle errors is up to you.

std::hex and std::dec are part of the <iomanip> streams that indicate how text is formatted. hex means hexadecimal, and dec means decimal. The default is decimal for integers and hexadecimal for pointers. For reasons unknown to me, there is no such thing as a hexadecimal representation for printing float or double, i.e. There is no "hexadecimal point", although support for C99 supports it.

+2
source

The code takes the optarg string and, considering 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, for this I usually use boost lexical_cast. For instance:

 int iMask = boost::lexical_cast< int >( strMask ); 
+2
source

This code uses manipulators to indicate that the stream expects integers to be read in base 16 (hex using the digits 0123456789ABCDEF), then extracts the hex from the string, storing it in iMask and using another manipulator to set the stream of strings back to default , expecting integers to be written in decimal form.

+1
source

Source: https://habr.com/ru/post/1341298/


All Articles