本文介绍了C ++ stringstreams与std :: hex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在工作中寻找代码。我有以下代码。在下面的代码中,最后一个语句的含义是什么?

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;

除了上面的问题:我有字符串输入,我需要知道如何转换一个使用C ++流的整数,而不是 atoi()

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;

对于上面的代码,如果我使用参数a运行, line asaand a second line output as 0.我不知道为什么,可以解释一下吗?

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?

推荐答案

最后一个语句创建一个临时的字符串流,然后使用它将十六进制格式的字符串解析为iMask。

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.

更好的是创建stringstream作为非临时的,理想情况下使用istringstream as您只使用它来解析字符串为int,然后检查转换是否成功。

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
}

你只需要将模式设置为十进制,如果你的stringstream现在要解析一个十进制整数。如果它要解析更多的十六进制的,你可以只读那些,例如,如果你有一堆的文件。

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.

如何处理错误是up给您。

How you handle errors is up to you.

std :: hex std :: dec 是指示文本应该被格式化的流的< iomanip> 部分的一部分。十六进制表示十六进制,十进制表示十进制。默认值是对整数使用十进制,对指针使用十六进制。由于我不知道的原因,没有一个十六进制表示为打印浮动或双,即没有十六进制点虽然C99排序支持它。

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.

这篇关于C ++ stringstreams与std :: hex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 03:21