Convert hexadecimal string with leading “0x” to signed short in C++?

前端 未结 6 847
孤城傲影
孤城傲影 2020-12-04 00:37

I found the code to convert a hexadecimal string into a signed int using strtol, but I can\'t find something for a short int (2 bytes). Here\' my p

6条回答
  •  余生分开走
    2020-12-04 00:54

    This should be simple:

    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";
    }
    

    While we are talking about files:
    You should NOT do this:

    while (!sCurrentFile.eof() )
    {
        getline (sCurrentFile,currentString);
        ... STUFF ...
    }
    

    This is because when you read the last line it does NOT set the EOF. So when you loop around and then read the line after the last line, getline() will fail and you will be doing STUFF on what was in currentString from the last time it was set up. So in-effect you will processes the last line twice.

    The correct way to loop over a file is:

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

提交回复
热议问题