The C language string to integer conversion

You might see on the Internet can be converted to an integer function with the following string:

  itoa(); //将整型值转换为字符串
  ultoa(); // 将无符号长整型值转换为字符串

Please note that the above function is not compatible with the ANSI standard, many compilers do not provide these functions, this article is not introduced, it does not make sense.

Convert integer to a string and can be compatible with the ANSI standard method is to use sprintf () and snprintf () function, in the actual development, we also do so.

1, the output of the integer / long integer into a string formatted

Standard C language provides the functions atoi and atol string into long integers, but does not provide the integer conversion / long integer into a string library functions, instead of using sprintf and snprintf function into a string formatted output.

Function declaration:

int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);

Example (book98.c)

/*
 * 程序名:book98.c,此程序演示格式化输出sprintf和snprintf函数。
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <string.h>

int main()
{
  int ii=1024;
  long ll=12345678901234;
  char strii[21],strll[21];

  memset(strii,0,sizeof(strii)); memset(strll,0,sizeof(strll));

  // 把整数ii转换为字符串,存放在strii中。
  sprintf(strii,"%d",ii);
  printf("strii=%s\n",strii);  // 输出strii=1024

  // 把长整数ll转换为字符串,存放在strll中。
  sprintf(strll,"%ld",ll);
  printf("strll=%s\n",strll);  // 输出strll=12345678901234

  memset(strii,0,sizeof(strii)); memset(strll,0,sizeof(strll));

  // 把整数ii转换为字符串,存放在strii中,只保留前10个字符。
  snprintf(strii,11,"%d",ii);
  printf("strii=%s\n",strii);  // 输出strii=1024

  // 把长整数ll转换为字符串,存放在strll中,只保留前10个字符。
  snprintf(strll,11,"%ld",ll);
  printf("strll=%s\n",strll);  // 输出strll=1234567890
}

operation result
Here Insert Picture Description

2 Notes

snprintf function performance under unix and windows platforms differ slightly, the Linux platform, reserved size-1 characters in the windows platform, reserved size characters.

3, Copyright

C Language Technology Network original article, reproduced please indicate the source link to the article, the author and original.

Source: C Language Technology Network ( www.freecplus.net )

Author: Ethics Code farming

If this article helpful to you, please praise support, or forwarded my article in your blog, thank you.

Guess you like

Origin www.cnblogs.com/wucongzhou/p/12668751.html