Search code examples
c++cprintfcoutkeil

How to use C++ streams with a c_str() library API.


Hi here is my code snippet:

RIT128x96x4StringDraw(HWREGBITW(&g_ulFlags, 0) ? "1" : "0", 48, 32, 15);

This is only used to print some string on the screen. I want a function or means to print numericals which can be increamented , like we do in c++

for(;;)
{ 
    cout<<i++;
}

Solution

  • From your other question Arm Cortex Display, we see the prototype of the function.

    void RIT128x96x4StringDraw(char *str, ulong x, ulong y, unsigned char level);
    

    Here are the parameters,

    • x and y are locations on the screen. They are character locations, so this function draws text like a printf() or cout.
    • The level parameter is an intensity; I guess you have a gray scale LCD and this is how white or black the text is.
    • str is a C string that you wish to print.

    Here is a sample that will print a number in a traditional C mode.

    #include <stdio.h>
    #include <stdlib.h>
    void print_number(int i)
    {
        char buffer[36];
        itoa (i,buffer,10);
        RIT128x96x4StringDraw(&buffer[0], 0, 0, 15);
    }
    

    This uses the itoa() function to convert a number to a C String. If you prefer C++ syntax, the following code may be more preferable,

    void print_number(int i)
    {
      std::ostringstream oss;
      oss << i++;
      /* What ever else you wish to do... */
      RIT128x96x4StringDraw(oss.str().c_str(), 0, 0, 15);
    }
    

    This code is not meant to be bullet proof production code and may not even compile. It is to demonstrate a concept.

    Here is an implementation of itoa() if your target is resource constrained.