function to convert string to integer in c language

One, atoi() function - converts the string str into an integer

1. The atoi function converts a string to an integer. Its meaning is the abbreviation of ASCII to integer.

2. Function description
1) Introduction Edit C language library function name
atoi
prototype:
int atoi(const char *nptr);
UNICODE
_wtoi()
2) Function description Edit parameter nptr string, if the first non-space character exists, it is a number Or the positive and negative signs start to do type conversion, and then stop the conversion when non-numeric characters (including the terminator \0) are detected, and return an integer number. Otherwise, zero is returned,
the required include header file: #include

Program example (1)

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
  float n;
  char *str = "12345.67";
  n = atoi(str);
  printf("string = %s integer = %f\n", str, n);
  return 0;
}

output:

string = 12345.67 integer = 12345.000000

Program example (2)

#include <stdlib.h>
#include <stdio.h>
int main()
{
  char a[] = "-100" ;
  char b[] = "123" ;
  int c ;
  c = atoi( a ) + atoi( b ) ;
  printf("c = %d\n", c) ;
  return 0;
}

output:

c = 23

Second, the atof() function - converts the string str into a double-precision value

grammar:

#include <stdlib.h>
  double atof( const char *str );

Function:
Convert the string str into a double-precision value and return the result. The parameter str must start with a valid number, but is allowed to end with any non-numeric character except "E" or "e".

Example:

   x = atof( "42.0is_the_answer" );

output:

   x=42.0

atol() function - converts a string to a long integer

grammar:

 #include <stdlib.h>
  long atol( const char *str );

Function:
Convert a string to a long integer and return the result. The function scans the parameter str string, skips the preceding space characters, does not start the conversion until it encounters a number or positive and negative symbols, and ends the conversion when it encounters a non-number or the end of the string, and returns the result.

Example:

  x = atol( "1024.0001" );

output:

  x=1024L

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326398507&siteId=291194637