milesmiles902:
I am trying to use sprintf to print characters on the screen. While searching around on C++ forums I found out that %c allows sprintf to use characters.
Is this the proper coding for such a situation? :
char switch[2] = "On"
…
char buffer[128];
sprintf(buffer,“”, switch);
client.println(buffer);
It doesn't seem to work properly. The document.getElementById doesn't complete its purpose of replacing SwitchState.
If there is a better way to use sprintf to print letters through a buffer. Please let me know.
That’s because switch is an array, and you are passing the pointer to the array, so %c is taking the bottom byte of where buffer is located, and putting it directly into the output. You would typically want to use %s to print a null terminated string. Note, in your declaration to switch, you want to use 3 bytes, to include the trailing null. Finally, switch is a C/C++ keyword.
So, you would want something like:
char switch_on_off[3] = "On";
....
char buffer[128];
sprintf(buffer,"<script>document.getElementById(\"SwitchState\").innerHTML=%s;</script>", switch_on_off);
client.println(buffer);
Sprintf is a big hammer, and it pulls in a lot of code. If you are just doing strings, it may be simpler to use strcpy and strcat:
char switch_on_off[3] = "On";
...
char buffer[128];
strcpy (buffer, "<script>document.getElementByld(\"SwitchState\").innerHTML=");
strcat (buffer, switch_on_off);
strcat (buffer, ";</script>");
client.println(buffer);
Now, if you normally have switch as a boolean, you can do:
bool switch_value = false;
...
char buffer[128];
strcpy (buffer, "<script>document.getElementByld(\"SwitchState\").innerHTML=");
strcat (buffer, (switch_value) ? "On" : "Off");
strcat (buffer, ";</script>");
client.println(buffer);
If speed was critical, you could optimize it further by keeping track of where the end of the string is, and use strcpy/memcpy to copy the string there, rather than having to search for the null byte. However, since you are building up a HTML document, and presumably sending it over the wire, speed is probably not critical at this point.