I need to do this in two separate steps but so far I am not finding a way of doing this.
First, I need to convert a double variable, into a char variable (and to be saved in that variable). I have noticed type casting doesnt work the same in C as Java / other languages. How do I cast a variable to be a string / char?
Second, I need to concatenate the strings, there will be a total of 6 string variables that will need concatenating, I have only found the strcat function which only takes 2 arguments.
These are the strings I am trying to build:
char *queryOne = "INSERT INTO location (id, carid, ownerid, lat, long, speed) VALUES (,2, 1, ";
char *queryTwo = lat; // lat is a double
char *queryThree = ",";
char *queryFour = longatude; // longatude is a double
char *queryFive = ",";
char *querySix = speed; // speed is a double
And then I need the concatenated string to work in: (mysql_query(conn, query)) as one long string
Edit: So possibly, this should convert the datatype I think?
char buffer [50];
char *queryOne = "INSERT INTO location (id, carid, ownerid, lat, long, speed) VALUES (,2, 1, ";
char *queryTwo = sprintf (buffer, "%d", lat);
char *queryThree = ",";
char *queryFour = sprintf (buffer, "%d", longatude);
char *queryFive = ",";
char *querySix = sprintf (buffer, "%d", speed);
fprintf(stderr, "Dta: %s\n", queryOne);
fprintf(stderr, "Dta: %s\n", *queryTwo);
fprintf(stderr, "Dta: %s\n", queryThree);
fprintf(stderr, "Dta: %s\n", *queryFour);
fprintf(stderr, "Dta: %s\n", queryFive);
fprintf(stderr, "Dta: %s\n", *querySix);
In your case, you could use:
#define MAXSQL 256
char sql[MAXSQL];
snprintf(sql, MAXSQL, "%s %f , %f , %f", queryOne, lat, longatude, speed);
The snprintf function writes onto the buffer, that is its first argument. http://www.cplusplus.com/reference/cstdio/snprintf/?kw=snprintf
Now you can use the sql string as you please.
Note that I used snprintf rather than sprintf. This is to avoid potential buffer overflows.
Also, don't use strcat so repeatedly, because that causes a Shlemiel the Painter algorithm, and every next call to strcat gets slower, because strcat has to start from the beginning and find the null terminator. See http://www.joelonsoftware.com/articles/fog0000000319.html for more info.
Related
I am trying to send values from ADC through USB using "CDC_Transmit_FS()"
On the receiving side, I am receiving data using readline() and decoding the 'string' to 'int'
The code works fine but occasionally I receive for example, b'\x00234\n' instead of b'1234\n', which raises decoding error.
Do you know why does '\x' appear?
One more question is: Is there any smarter method to send ADC values through USB instead of converting int values to string?
I want to make the transmission faster.
thanks in advance!
uint32_t adcbuff[sample];
char endofpacket[5] = {'9', '9', '9', '9', '\n'};
char txbuff[sample*5];
while(1)
{
HAL_ADC_Start_DMA(&hadc2,(uint32_t*)adcbuff, sample);
for(i = 0; i < sample; i++)
{
sprintf (tempbuff, "%u\n", ((adcbuff[i] * 5000) / 0xFFFF)-2000);
strcat( txbuff,tempbuff);
}
strcat( txbuff,endofpacket);
CDC_Transmit_FS( (uint8_t*)txbuff, strlen(txbuff));
strcpy(txtbuff,"");
}
not enough rep to post as a comment
Usually \x is an indication of a hexadecimal value. Could it be that a non alphanumeric value is being received?
For troubleshooting, I would temporarily change
sprintf (tempbuff, "%u\n", ((adcbuff[i] * 5000) / 0xFFFF)-2000); to
sprintf (tempbuff, "%s\n", ((adcbuff[i] * 5000) / 0xFFFF)-2000); to see what kind of characters are being sent over. (Maybe sprintf to a tmp file instead.)
b'\x00234\n' - This means that first byte is 0! Not ASCII 0 = 0x30, but just 0.
Probably this is effect of strcat - after concatenating this function adds '\0' at the end of string.
Instead of using sprintf, just redirect stdout to USB-CDC and use printf:
int _write(int file, char *ptr, int len)
{
UNUSED(file);
CDC_Transmit_FS((uint8_t*)ptr, len);
while (hcdc->TxState != 0);
return len;
}
If you want to send all at once use setvbuf for stdout with _IOFBF and call fflush(stdout);
I am willing to transfer data from unsigned char hash[512 + 1] to char res[512 + 1] safely.
My C hashing library MHASH returns a result so it can be printed as listed below.
for (int i = 0; i < size /*hash block size*/; i++)
printf("%.2x", hash[i]); // which is unsigned char - it prints normal hash characters in range [a-z,0-9]
printf("\n");
I am willing to do something like that (see below).
const char* res = (const char *)hash; // "hash" to "res"
printf("%s\n", res); // print "res" (which is const char*) - if i do this, unknown characters are printed
I know the difference between char and unsigned char, but I don't know how to transfer data. Any answer would be greatly appreciated, thanks in advance. But please do not recommend me C++ (STD) code, I am working on a project that is not STD-linked.
Given that the contents of the unsigned char array are printable characters, you can always safely convert it to char. Either a hardcopy with memcpy or a pointer reference as in the code you have already written.
I'm guessing that the actual problem here is that the unsigned char array contents are not actually printable characters, but integers in some format. You'll have to convert them from integer to ASCII letters. How to do this depends on the format of the data, which isn't clear in your question.
Assuming the following:
#define ARR_SIZE (512 + 1)
unsigned char hash[ARR_SIZE];
char res[ARR_SIZE];
/* filling up hash here. */
Just do:
#include <string.h>
...
memcpy(res, hash, ARR_SIZE);
Well, thank you guys for your answers, but unfortunately nothing worked yet. I am now sticking with the code below.
char res[(sizeof(hash) * 2) + 1] = { '\0' };
char * pPtr = res;
for (int i = 0; i < hashBlockSize; i++)
sprintf(pPtr + (i * 2), "%.2x", hash[i]);
return (const char *)pPtr;
Until there is any other much more performant way to get this done. It's right, my question is strongly related to MHASH Library.
res = PQexec(db, "SELECT username, msg, ts, lat, lon FROM tweet");
rows = PQntuples(res);
cols = PQnfields(res);
printf("Getting %d rows\n", rows);
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
msg = PQgetvalue(res, i, j);
printf("%s\t", msg);
}
putchar(10);
}
PQclear(res);
.
username
msg
ts (lat, lon)
I want the printed table to be in the format I have above, but it gets printed out all on a single line. How do I add newlines and format column queries to be wrapped in parenthesis or be between commas, etc.
Simply change the \t to a \n like so
printf("%s\n", msg);
If you want to change the formatting, you can do something like this:
Assign each result to variables:
char *uname, *msg, *ts, *lat, *lon;
Then, use a temporary:
char *res = malloc(/*pick a safe size*/);
sprintf(res, "%s\n%s\n%s (%s, %s)\n", uname, msg, ts, lat, lon);
printf(res);
Alternatively, you can skip the assigning to res and use
printf("%s\n%s\n%s (%s, %s)\n", uname, msg, ts, lat, lon);
instead
I want to have an infinite loop
getting command each loop,
and this is my code
while ( 1 )
{
char * command[100];
printf("---| ");
scanf( "%[^\n]",command);
printf("%s\n",command);
}
for some reason it only inputs once and
the loop doesnt terminate with asking the input.
what did i do wrong here?
The definition should be
char command[100];
And not char *command[100] - this is a array of 100 char pointers.
Also scanf() is not easy to use, I would use fgets(command, sizeof(command), stdin);
and then remove the newline.
while ( 1 )
{
char command[100];
printf("---| ");
scanf( "%s", command);
printf("%s\n",command);
}
I'm doing a small app for evaluating and analyzing transfer functions. As boring as the subject might seem to some, I want it to at least look extra cool and pro and awesome etc... So:
Step 1: Gimme teh coefficients! [A bunch of numbers]
Step 2: I'll write the polynomial with its superscripts. [The bunch of numbers in a string]
So, I write a little C parser to just print the polynomial with a decent format, for that I require a wchar_t string that I concatenate on the fly. After the string is complete I quickly try printing it on the console to check everything is ok and keep going. Easy right? Welp, I ain't that lucky...
wchar_t *polynomial_description( double *polyArray, char size, char var ){
wchar_t *descriptionString, temp[100];
int len, counter = 0;
SUPERSCRIPT superscript;
descriptionString = (wchar_t *) malloc(sizeof(wchar_t) * 2);
descriptionString[0] = '\0';
while( counter < size ){
superscript = polynomial_utilities_superscript( size - counter );
len = swprintf(temp, 100, L"%2.2f%c%c +", polyArray[counter], var, superscript);
printf("temp size: %d\n", len);
descriptionString = (wchar_t *) realloc(descriptionString, sizeof(wchar_t) * (wcslen(descriptionString) + len + 1) );
wcscat(descriptionString, temp);
counter++;
}
//fflush(stdout); //Already tried this
len = wprintf(L"%ls\n", descriptionString);
len = printf("%ls**\n", descriptionString);
len = fprintf(stdout, "%ls*\n", descriptionString);
len = printf("FFS!! Print something!");
return descriptionString;
}
During the run we can see temp size: 8 printed the expected number of times ONLY WHILE DEBUGGING, if I run the program I get an arbitrary number of prints each run. But after that, as the title states, wprintf, printf and fprintf don't print anything, yet len does change its size after each call.
In the caller function, (application:(UIApplication *)application didFinishLaunchingWithOptions:, while testing) I put an NSLog to print the return string, and I dont get ANYTHING not even the Log part.
What's happening? I'm at a complete loss.
Im on XCode 4.2 by the way.
What's the return value from printf/wprintf in the case where you think it's not printing anything? It should be returning either -1 in the case of a failure or 1 or more, since if successful, it should always print at least the newline character after the description string.
If it's returning 1 or more, is the newline getting printed? Have you tried piping the output of your program to a hex dumper such as hexdump -C or xxd(1)?
If it's returning -1, what is the value of errno?
If it turns out that printf is failing with the error EILSEQ, then what's quite likely happening is that your string contains some non-ASCII characters in it, since those cause wcstombs(3) to fail in the default C locale. In that case, the solution is to use setlocale(3) to switch into a UTF-8 locale when your program starts up:
int main(int argc, char **argv)
{
// Run "locale -a" in the Terminal to get a list of all valid locales
setlocale(LC_ALL, "en_US.UTF-8");
...
}