跳至正文
View Categories

< 1 min read

主要内容 #

sprintf(s, “%d”, N) #

函数说明:将数字 N 转化成字符串 s。
请看例程:

#include < iostream >
#include < string >
#include <stdio.h>
using namespace std;
int main()
{
    char dashima[3];//可以写更大的数字例如:dashima[10]
    int n = 125;
    sprintf(dashima,"%d",n);
    printf("%s", dashima);
    
    return 0;
}

注意,sprintf 本身是用于字符串的格式化的。它的使用方式和 printf 相类似。

请看例程:

#include < iostream >
#include < string >
#include <stdio.h>
using namespace std;
int main()
{
    char dashima[100];
    int n = 125;
    sprintf(dashima, "Eg-1, Time: %d:%d.", 12, 30);
    printf("%s\n",dashima);
    printf("Eg-2, Time: %d:%d.\n", 12, 30);

    return 0;
}

sscanf(s, “%d”, &N) #

函数说明:将字符串 s 转化成数字 N。
请看例程:

#include < iostream >
#include < string >
using namespace std;
int main()
{
    string a = "29";
    int n = 0;

    sscanf(a.c_str(), "%d", &n); // 注意引用符号
    cout << n << endl;
    
    return 0;
}

注意,sscanf 本身是用于字符串内容解析。它的使用方式和 scanf 相类似。

请看例程:

#include < iostream >
#include < string >
using namespace std;
int main()
{
    string str = "12:30";
    int a, b;
    sscanf(str.c_str(), "%d:%d", &a, &b);

    return 0;
}

习题 #

请试一试完成下面的练习:

1. 请定义两个函数,分别完成 float 和 字符串之间的互相转化。

2. 请提取字符串"X=125.2, Y=15.26, Z=1.0"中的数字。

3. 请将数字"3.1415926"转化成字符串,并保留2位小数。