Reputation: 119
Function should return printf
value of float
of type char str*
Inputs:
char *string = "%f";
float k = 1.0005325678910
Function:
My function takes input string %f
and float value 1.0005325678910
as inputs storing the value of printf
in char *answer
.Here I am unable to allocate memory for char *answer
int length(char* string){
int i = 0;
while (string[i] != '\0')
i++;
return i;
}
char *res(char *string, float k){
int len = length(string); //len is a function which return length of the string
char *answer = (char*)malloc(sizeof(char)*len);
sprintf(answer,format, n);
//printf("%05d", 50);
//printf("%s", sqlAnswers);
return answer;
}
Expected Output:
char *output = 1.000532;
Bug:
allocation of memory to char *answer
Output: 1.000533
My code should not round the last digit.
Edit:
Ex: If my float k = 6.143211
then expected Output should be 6.14
but the function returns 6.15
which rounds the last digit.
Upvotes: 0
Views: 90
Reputation: 223553
It appears you are trying to do this:
#include <stdio.h>
#include <stdlib.h>
char *res(char *format, float k)
{
// Ask snprintf to report how many bytes are needed.
int t = snprintf(NULL, 0, format, k);
if (t < 0)
{
fprintf(stderr, "Encoding error.\n");
exit(EXIT_FAILURE);
}
// Allocate space for those bytes and a null terminator.
char *result = malloc(t+1);
if (!result)
{
fprintf(stderr, "Allocation error.\n");
exit(EXIT_FAILURE);
}
// Format the number.
snprintf(result, t+1, format, k);
return result;
}
int main(void)
{
char *b = res("%f", 1.0005325678910);
puts(b);
free(b);
}
Upvotes: 2
Reputation: 12332
The general C way to do this is to pass in a char * buf and size_t len. Then return how many chars have been or would have been written to the buffer.
But if you want to write a function that allocates a buffer of the right size you have 2 choices:
1) always allocate the maximum size for "%2f". Given the size that's probably the best. It's not worth the CPU overhead to compute the right size to save a byte here or there.
2) find out the right length using:
char c;
int len = snprintf(&c, 1, "%2f, k);
assert(len >= 0);
++len;
or output to a fixed sized buffer and then use strdup(). Sort of a combination of 1 and 2.
Upvotes: 0