Could somebody help me(sorry for the english), Im trying to convert a string to a double but when I can't get it here's my code(thank you, I'll appreciate help so much):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LONG 5
char bx[MAX_LONG];
double cali=0;
int main() {
scanf("%c",bx);
cali = strtod(bx,NULL);
printf("%f",cali);
return 0;
}
when I input a value greater than 10 in the output it just print the first number like this:
input: 23
output: 2.00000
input: 564
output: 5.00000
The scanf()
specifier you are using is wrong, unless you specify a number of characters, but then the array will not be nul
terminated, I suggest the following
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char bx[6]; /* if you want 5 characters, need an array of 6
* because a string needs a `nul' terminator byte
*/
double cali;
char *endptr;
if (scanf("%5s", bx) != 1)
{
fprintf(stderr, "`scanf()' unexpected error.\n");
return -1;
}
cali = strtod(bx, &endptr);
if (*endptr != '\0')
{
fprintf(stderr, "cannot convert, `%s' to `double'\n", bx);
return -1;
}
printf("%f\n", cali);
return 0;
}