C language strings and Numbers of the mutual conversion code

  • 2020-04-02 01:08:27
  • OfStack

1. Convert Numbers to strings
Sprintf is almost identical in usage to printf, except that it is printed to a different destination, the former to a string, and the latter to the command line.
Sprintf is a variable parameter function, defined as follows:
Int sprintf(char *buffer, const char *format [, argument]... );
In addition to the first two parameter types fixed, can be followed by any number of parameters.
Printf and sprintf USES formatted string to a specified string format, the format string used within some starting with "%" format specifier (the format specifications) to occupy a position in the back and provide the corresponding variables in the list, the final function with the corresponding position of the variable to replace the specifiers, produce a caller to a string.
For example, the integer 123 is printed as a string and stored in s.
Sprintf (s, \ \ "% d", 123); / / the \ "123 \"

2. Convert a string to a number
Function name: atol
Power: converts a string into an integer
How to use: long atol(const char * NPTR);
Application:


#include <stdlib.h>
  #include <stdio.h>
  int main(void)
  {
  long l;
  char *str = "98765432";
  l = atol(str); 
  printf("string = %s integer = %ldn", str, l);
  return(0);
  }


Related articles: