1

I am trying to extract the instance number from a DICOM image using dcmtk. The code is shown below:

DcmFileFormat fileformat;
    OFCondition status = fileformat.loadFile(src_path);
    if (status.good())
      {
        OFString instanceNumber=0;
        if (fileformat.getDataset()->findAndGetOFString(DCM_InstanceNumber, instanceNumber).good())
        {
            std::cout << "instance Number N: " << instanceNumber << std::endl;
            sprintf(instanceNum, "%s\n", instanceNumber);

            printf("%s\n", instanceNum);
        }
        else
            std::cerr << "Error: cannot access instance Number!" << std::endl;
       }
    else
        std::cerr << "Error: cannot read DICOM file (" << status.text() << ")" << std::endl;

Now I got the instance number,but I want to copy the instance number into a char or string( for further programming).But as the number is an OFString,how do I convert it into the required datatype. Any thoughts?

Abhishek V. Pai
  • 241
  • 1
  • 10
  • 27

4 Answers4

3

Actually, OFString implements a subset of std::string, so you can use c_str() if you want to get a "const char*" as other people already suggested. Alternatively, you could also compile the DCMTK with HAVE_STD_STRING defined and OFString would be identical to std::string.

All this is also described in the documentation, of course.

J. Riesmeier
  • 1,641
  • 10
  • 14
1

You use c_str() to get a const char* and create a string based on that if you want.

std::string s(instanceNumber.c_str());
Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
1

You can use dcmtk to directly read into the requested data type with the findAndGetXXX-methods. In your particular case the VR of the Instance Number is IS, so the method to use is findAndGetSint32. See: here.

Applied to your code:

DcmFileFormat fileformat;
OFCondition status = fileformat.loadFile(src_path);
if (status.good())
  {
    SInt32 instanceNumber=0;
    if (fileformat.getDataset()->findAndGetSint32(DCM_InstanceNumber, &instanceNumber).good())
    {
        std::cout << "instance Number N: " << instanceNumber << std::endl;
        sprintf(instanceNum, "%d\n", instanceNumber);

        printf("%d\n", instanceNum);
    }
    else
        std::cerr << "Error: cannot access instance Number!" << std::endl;
   }
else
    std::cerr << "Error: cannot read DICOM file (" << status.text() << ")" << std::endl;

shoud be working...

Markus Sabin
  • 3,916
  • 14
  • 32
0

In some cases (e.g. Debian), the operating system provides the packages compiled with the flag DCMTK_ENABLE_STL disabled. Patching the package is not a good idea, because then you'd have to recompile every package that depends on it.

But sometimes you do need a std::string and an OFString won't do. To convert an OFString to an std::string in general, you can use the following snippet:

std::string str(ofstr.data(), ofstr.length());

which also copies any embedded zeros if there are any.

Pedro Gimeno
  • 2,837
  • 1
  • 25
  • 33