数字转化为字符串,sprintf使用(弱菜笔记)

注明:以下例程均在code::bolcks(编译器GNU GCC)下运行通过,如果读者不能正确运行,请尝试调整编译器为GNU或GCC。

我们通过几个例子认识sprintf的用法,由此也初窥数字转化为字符串中数据的门径。

最简单直接的方法:一个数字加上0的ASC2码就得到对应字符的ASC2码。

//Example #1
#include <stdio.h>

int main()
{
    int a[3]={0, 1, 2};
    char s[4];
    for(int i = 0; i<3; i++)
        s[i] = a[i] + '0';
    s[3] = '\0';
    puts(s);
}

输出:012


更简洁的方法是使用sprintf,“sprintf”可以理解为“打印到字符串的函数”。

//Example #2
#include <stdio.h>

int main()
{
    char s[10];
    int x, y;
    while(scanf("%d%d", &x, &y) != EOF)
    {
        sprintf(s, "%d%d", x, y);//将x,y储存的数据转化为字符串s中的数据
        puts(s);
    }
    return 0;
}
输入:1 2

输出:12

在上例中,语句

sprintf(s, "%d%d", x, y);

我理解为是将“%d%d”转化为字符串s的内容,而“%d%d”就是“12”。

以下还有一个例子,摘自C++ reference

//Example #3
#include <stdio.h>

int main ()
{
  char buffer[50];
  int n, a=5, b=3;
  //建立字符串buffer,n是buffer的长度,包括空格但不包括‘\0’
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a %d char long string\n",buffer,n);
  return 0;
}
输出:[5 plus 3 is 8] is a 13 char long string



原文地址:https://www.cnblogs.com/cszlg/p/2910579.html