1

I've been googling but I haven't found a simple float to char using the sprintf function. So far - this is all I've written in my small code section. The problem is that I always get a 0 return.

   int main()
   {
        float num_input[9];
        printf("Enter a real number: ");
        scanf("%f", &num_input);
        printf("%f", num_input);
        char str_num[9];
        sprintf(str_num, "%f", &num_input);
        printf(str_num);

        return 0;
    }

Thank you to everyone that helped! I finally saw what I did wrong and learnt more. The final code written was:

float num_input[9];
printf("Enter a real number: ");
scanf("%f", &num_input);
char str_num[9];
int index = 0;
sprintf(str_num, "%f", num_input[index]);
4
  • float num_input[9];--> float num_input; and printf(str_num); --> puts(str_num); Commented Jun 16, 2016 at 5:41
  • 2
    Look at your compiler warnings and fix those before even considering requesting for help. Or ask about the warnings if you do not understand them. That will save everyone alot of time. Commented Jun 16, 2016 at 5:43
  • In addition to @SouravGhosh comments: sprintf(str_num, "%f", &num_input); --> sprintf(str_num, "%f", num_input); Commented Jun 16, 2016 at 5:44
  • @kaylum I don't have any compiler warnings. That's the problem. When I go to print out the %c I just get a 0 Commented Jun 16, 2016 at 7:06

1 Answer 1

3

sprintf(str_num, "%f", &num_input); is wrong. You should use something like:

sprintf(str_num, "%f", num_input[index]);  /* 0 <= index < 9 */
/*                    ^          ^^^^^  */

After this keep the fingers crossed that str_num doesn't overflow.

Remember that "%f" specifier of printf family of function should have a matching double or float (float becomes double after default argument promotion).


Perhaps you should make the similar fix for scanf and printf also:

scanf("%f", &num_input[0]);
printf("%f", num_input[0]);
Sign up to request clarification or add additional context in comments.

4 Comments

Why do you need float num_input[9] in the first place. The whole program will work with a single float num_input and OP is not using the other 8 floats in the array.
@RishikeshRaje I am using it actually but I didn't include that part of my code.
Thank you so much! I finally got the code sorted! float num_input[9]; printf("Enter a real number: "); scanf("%f", &num_input); char str_num[9]; int index = 0; sprintf(str_num, "%f", num_input[index]);
scanf should be changed to scanf("%f", &num_input[index]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.