Converting string to int or float in C

C lanuguage provides following string to number conversion programs in stdlib.h

  • atoi : Converts a string to an integer
  • atof : Converts string to floating point number

 

Here is an example :

/*
 ============================================================================
 Name        : Hello.c
 Author      : 
 Version     :
 Copyright   : TopJavaTutorial.com
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  char* str1 = "123.45";
  char* str2 = "678";

  float number1;
  int number2;

  printf("String 1 is %s", str1);
  printf("\nString 2 is %s", str2);

  //convert string to float
  number1 = atof(str1);

  printf("\nString 1 converted to float is %.2f", number1);

  //convert string to int
  number2 = atoi(str2);

  printf("\nString 2 converted to int is %d", number2);

  return EXIT_SUCCESS;
}

Output :


String 1 is 123.45
String 2 is 678
String 1 converted to float is 123.45
String 2 converted to int is 678

 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags