Reputation: 173
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
Upvotes: 2
Views: 281
Reputation: 46
You should try this changes to make it work.
First: Change
scanf("%c",bx); /*Here you're reading a single char*/
To this:
scanf("%s",bx);/*Now you're reading a full string (No spaces)*/
Second: Change
cali = strtod(bx,NULL);
To this:
cali = atof(bx);
This i think will work perferct For you.
Upvotes: 0
Reputation: 53006
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;
}
Upvotes: 2