C: Conversion from String to Double gives strange results - c

I am tring to convert a string into a floating-point value. Take a look at my small program:
#include <stdio.h>
int main() {
char string[3] = "42";
double value = atof(string);
printf("Floating-point value: %f\n", value);
return 0;
}
When I run it, I get this:
Floating-point value: 327680.000000
Why? The conversion from string to integer using atoi has worked very well!
If you have any idea why this is, please share your wisdom. :)

char string[2] = "42";
should be
char string[3] = "42";
the size of "42" array is 3 bytes as you have to count the trailing null character. If you want use char string[2] for the declaration, your string will not be null terminated.
Then you also have to include stdlib.h file for atof declaration:
#incude <stdlib.h>

Related

Is there any difference in the way atof and strtod work?

I know that strtod() and atof() functions are used for conversion from string to double.
But I can't figure out the difference between these two functions.
Is there any difference between these two functions, if yes then please let me know...
Thanks in Advance.
From the man page on double atof(const char *nptr):
The atof() function converts the initial portion of the string pointed to by nptr to double. The behavior is the same as
strtod(nptr, NULL);
except that atof() does not detect errors.
Why can't it detect errors? Well, because that second argument of double strtod(const char *nptr, char **endptr) is used to point to the last character that couldn't be converted, so you can handle the situation accordingly. If the string has been successfully converted, endptr will point to \0. With atof, that's set to NULL, so there's no error handling.
An example of error handling with strtod:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *str = "1234.56";
char *err_ptr;
double d = strtod(str, &err_ptr);
if (*err_ptr == '\0')
printf("%lf\n", d);
else
puts("`str' is not a full number!");
return 0;
}

How does one correctly format the atoi function?

I'm trying to acquaint myself with the atoi function, so I wrote a basic programme using it, but I'm having some problems:
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
int main(void)
{
string s = get_string("String:");
int i = get_int("Integer:");
int a = atoi(s[1]);
int j = i + a;
printf("%i\n", j);
}
When I try to compile it, I get the error message "incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]". This seems to suggest that it wants something to do with a char, but from what I've read, I was under the impression that atoi was used with strings. If someone could explain where I'm going wrong, I'd be very thankful
You're passing a char(assuming string is a typedef for char*) by indexing the string and it wants you to pass a char*. So just pass the full string:
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
int main(void)
{
string s = get_string("String:");
int i = get_int("Integer:");
int a = atoi(s);
int j = i + a;
printf("%i\n", j);
}
here is the syntax for atoi()
int atoi(const char *nptr);
Notice the parameter is a pointer, not a single character.
However, the posted code has:
int a = atoi(s[1]);
which is a single character, not a pointer
suggest:
int a = atoi( s );
Also, the function: atoi() has no facility to let the program know when an error occurred. Suggest using the strtol() function which does have a facility to indicate when an error occurred

Converting double into ascii in C

I hope this isn't a stupid question, but say I want to create a char* in C called "Hello World", using only a double. I want to do this by abusing type confusion, so that in one file I might have something like this:
char test[12];
int main() {
printf("%s\n", test);
}
and in the other file I'd have this:
double test = some_random_double;
So my issue is therefore in picking a double that converts into the Ascii string "Hello World".
Are there any suggestions? I thought I would go backwards and convert the ascii string into hex or binary, and then try converting said hex/binary into a float format, but I can't figure out how to do so.
You would need an array of 2 doubles for this purpose.
You can determine what values with this code:
#include <stdio.h>
#include <string.h>
int main(void) {
char msg[sizeof(double) * 2] = "Hello World";
double d[2];
memcpy(d, msg, sizeof(d));
printf("double test[2] = { %.20lg, %.20lg };\n", d[0], d[1]);
return 0;
}
Executing it on my laptop produces:
double test[2] = { 2.1914441197069634153e+228, 3.2516248670450380385e-317 };

How to convert char pointer to float in C?

I've looked around everywhere and tried pretty much everything suggested and can't get anything to work.
this is my code:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(){
float a;
char *nums[3];
char str[5];
printf("Please enter a,b,c:");
scanf("%s",str);
int i=0;
char *p;
p = strtok (str,",");
while (p != NULL)
{
nums[i++] = p;
p = strtok (NULL, ",");
}
a=atof(nums[0]);
printf("%s\n",nums[0]);
printf("%f\n",a);
return 0;
}
the math.h is for something later on after I figure this out. So if I entered "1,2,3" into this program, my print statements would show me "1" and then "0.000", this is obviously just there for me to test things out but why the does my value just disappear after trying to convert to a float? I need that value of 1 to do math with later in my program but I can't get that char pointer value no matter what I try, I can only seem to print it, but it screws up as soon as I try to convert it into a type I can use.
Two issues:
You nums and str arrays are too short. nums should have a size of at least 3, and str should be at least 6 ("1,2,3" plus null byte), probably more for larger numbers.
So change those to:
char *nums[3];
char str[20];
Second, you don't #include <stdlib.h>, which contains the declaration of atof. Without a declaration, it is assumed to return an int.
Fix the array sizes, and #include <stdlib.h>, and it should work.

Converting command line arguments to decimals in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am writing a program that takes command line arguments and performs basic arithmetic operations on them. I am using getopt to get the arguments and I am storing them as strings. Below are the variables I store the arguments in
char *distance = NULL;
char *time = NULL;
char *pace = NULL;
However how do I then convert them to decimals? So for example "5" will become 5.00 or "6.12" will become 6.12. I have tried search around but other solutions don't seem to work for me.
I have tried doing
double testnum;
testnum = atof(time);
but I get
error: request for member 'testnum' in something not a structure or a union
You can also try strtof()
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *string, *stopstring;
double x;
float f;
long double ld;
string = "3.1415926This stopped it";
f = strtof(string, &stopstring);
printf("string = %s\n", string);
printf("strtof = %f\n", f);
printf("Stopped scan at \"%s\"\n\n", stopstring);
}
Just use atof:
double atof (const char* str);
Parses the C string str, interpreting its content as a floating point number and returns its value as a double.
It's not particularly robust though: in particular it returns zero if the input is not convertible, and undefined behaviour if the input number is too big.
Take a look at the atof function. it takes a char * and tries to parse a double.
You can start off by scanf with the appropriate type.
scanf("%f", &time);
and then use printf to convert a type to a string when necessary.
If you do need to convert types from string, look for an atoX style function to do the conversion. For example, here is a program that converts a (ascii) to i (integer)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int val;
char str[20];
strcpy(str, "98993489");
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);
strcpy(str, "tutorialspoint.com");
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);
return(0);
}enter code here
The example code you provide does not match the error you have. The error tells us that testnum is not found in a structure.
I'm guessing you have a pointer to the structure and use non-pointer . to access the member. Or that you have a non-pointer structure and use pointer -> to access the member.

Resources