How do you produce char * for int or double in C

Sorry if this is a very simple question, but I am very new to C. I want to embed char * s in doubles and ints and cannot find an explanation as to how.

Edit: I am reading user input, which is char *. I want to convert half of the input, say, β€œ23” to 23 and half from, for example, from β€œ23.4” to 23.4.

+6
source share
2 answers

You can use char* as follows:

 char *c = "123.45"; int i = (int) c; // cast to int double d = (double) c; // cast to double 

But this will give meaningless results. It simply forces the pointer to be treated as an integer or double.

I assume that you want to parse (not translate) the text into int or double . Try the following:

 char *c = "123.45"; int i = atoi(c); double d = atof(c); 
+13
source

Strictly speaking, you can do this: (int) pointer.

However, you are probably looking for the atoi and atof functions.

atoi is a function that converts a char * pointing to a string containing an integer in the decimal value of an integer.

atof is similar for double.

+2
source

Source: https://habr.com/ru/post/910215/


All Articles