Answers in the forum

Somebody asked how to convert an integer to a string. ( int A=123 to a String V='123').
The normal answer seems to be "Use Serial.println()".

Please can somebody tell, how using Serial.print helps, if you do not want the value printed to serial port, but wan to have a string, which can be handled further .

Try - GitHub - RobTillaart/PrintString: Arduino library to print to a String
or - GitHub - RobTillaart/PrintCharArray: Arduino library to print to a char array

I'm not sure I've got what you're asking for, but why not using the "String()" function?

  int a = 123;
  String v = String(a);

PS: please don't use capital letters for variables, the're conventionally "reserved" to indicate constant values...

1 Like

This is the simple (corrected typo) command, I have been using.
Never understood, why some recommend this Serial.print().
Normally I newer use one character variable names nor uppercase, but here they were just for example.

What is that?

I guess another edit is coming?

It doesn't

Can you please provide one or more references where it's suggested to use Serial.println()?

I suspect that it all depends on the use case where you see it. The most common case that I'm aware of is where a user wants to print an integer, first converts it to String (which probably fails and hence a question); the advice in that case is why to convert in the first place and not just use Serial.print().

One use case would be to show it on a TFT or Oled display where you can't use print.

-jim lee

It doesn't. But perhaps you misremembered or misunderstood the advice?

There is the sprinf() function which can be used convert integer, and other value types, to string.

Notice I say "string" rather than "String". They are different things in C++.

but how does sprintf() or the underlying functions do it

i imagine something like

void
convert (
    int val )
{
    int  num  = val;
    int  dec  = 0;
    int  base = 1;

    printf ("%s: %6d\n", __func__, val);

    for ( ; val; val /= 10)  {

        int dig = val % 10;
        dec     = (dec << 4) + dig;
     // dec    += base * dig;
        base    = base * 16;

        printf ("   %6d", val);
        printf ("   %6d", dig);
        printf ("   %6x", dec);
        printf ("   %6d", base);
        printf ("\n");
    }

    char s [10];
    memset (s, 0, sizeof(s));

    for (int i = 0; dec; dec >>= 4, i++)  {
        s [i] = '0'+ (dec & 0xF);
        printf (" %6d - '%6s' %d - %x\n", num, s, i, dec & 0xf);
    }
}

Ok, so does my answer (about the "String()" function) on post #3 is what you were looking for?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.