Search code examples
c++builder

How to print a String in a C++ Builder console application?


I am trying to print the contents of a String in a console application. I am doing a test and would like to visualize the content for debugging purposes.

Here is my code:

bool Tests::test001() {
    std::string temp;

    CDecoder decoder;  // Create an instance of the CDecoder class
    String input = "60000000190210703800000EC00000164593560001791662000000000000080000000002104302040235313531353135313531353153414C4535313030313233343536373831323334353637383930313233";
    String expected_output = "6000000019";
    String output = decoder.getTPDU(input);  // Call the getTPDU method
    std::cout << "Expected :" << expected_output.t_str() <<std::endl;
    std::cout << "Obtained :" << output.t_str() <<std::endl;
    
    return output == expected_output;  // Return true if the output is as expected, false otherwise
}

This is what I get:

Running test: 0 Expected :024B8874 Obtained :00527226 Test Fail Press any key to continue...

This is what I want to get:

Running test: 0 Expected :6000000019 Obtained :0000001902 Test Fail Press any key to continue...

Here the Obtained value is a substring of the input I chose randomly (a shift to the left by two characters).

Whether I use t_str() or c_str() the result is the same.


Solution

  • In C++Builder 2009 and later, String (aka System::String) is an alias (ie, a typedef) for System::UnicodeString, which is a UTF-16 string type based on wchar_t on Windows and char16_t on other platforms.

    Also, the UnicodeString::t_str() method has been deprecated since around C++Builder 2010. In modern versions, it just returns the same pointer as the UnicodeString::c_str() method.

    You can't print a UnicodeString's characters using std::cout. You are getting memory addresses printed out instead of characters, because std::cout does not have an operator<< defined for wchar_t*/char16_t* pointers, but it does have one for void* pointers.

    You need to use std::wcout instead, eg:

    std::wcout << L"Expected :" << expected_output.c_str() << std::endl;
    std::wcout << L"Obtained :" << output.c_str() << std::endl;
    

    If you want to use std::cout, you will have to convert the String values to either System::UTF8String (and put the console into UTF-8 mode) or System::AnsiString instead, eg:

    std::cout << "Expected :" << AnsiString(expected_output).c_str() << std::endl;
    std::cout << "Obtained :" << AnsiString(output).c_str() << std::endl;