在C ++中将带有前导“ 0x”的十六进制字符串转换为带符号的缩写?

gra*_*amm 2 c++ string int hex short

我找到了将十六进制字符串转换为signed intusing 的代码strtol,但找不到短整数(2个字节)的内容。这是我的代码:

while (!sCurrentFile.eof() )
{
    getline (sCurrentFile,currentString);
    sOutputFile<<strtol(currentString.c_str(),NULL,16)<<endl;
}
Run Code Online (Sandbox Code Playgroud)

我的想法是读取一个具有2个字节宽的值的文件(如0xFFEE),将其转换为带符号的int并将结果写入输出文件中。执行速度不是问题。

我可以找到一些避免该问题的方法,但是我想使用“单行”解决方案,所以也许您可以为此提供帮助:)

编辑:文件看起来像这样:

while (!sCurrentFile.eof() )
{
    getline (sCurrentFile,currentString);
    sOutputFile<<strtol(currentString.c_str(),NULL,16)<<endl;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我已经尝试了十六进制运算符,但这样做之前我仍然必须将字符串转换为整数。

// This won't work as currentString is not an integer
myInt << std::hex << currentString.c_str(); 
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 5

这应该很简单:

std::ifstream   file("DataFile");
int             value;

while(file >> std::hex >> value)  // Reads a hex string and converts it to an int.
{
    std::cout << "Value: " << std::hex << value << "\n";
}
Run Code Online (Sandbox Code Playgroud)

虽然我们谈论的文件:
你应该这样做:

while (!sCurrentFile.eof() )
{
    getline (sCurrentFile,currentString);
    ... STUFF ...
}
Run Code Online (Sandbox Code Playgroud)

这是因为当你读到最后一行它设置EOF。因此,当您循环然后在最后一行之后读取该行时,getline()将会失败,并且您将对上一次设置时currentString中的内容进行STUFF。因此,实际上,您将对最后一行进行两次处理。

循环遍历文件的正确方法是:

while (getline(sCurrentFile,currentString))
{
    // If the get fails then you have read past EOF and loop is not entered.
    ... STUFF ...
}
Run Code Online (Sandbox Code Playgroud)