sscanf与sprintf函数

sscanf

sscanf函数可以从一个给定的字符串中把格式化字符串中的内容提取出来,若匹配成功,该函数返回成功匹配和赋值的个数。如果到达文件末尾或发生读错误,则返回 EOF。函数接口如下:

int sscanf(const char *str, const char *format, ...)

其中str是源字符串,format是格式化字符串

实例

#include 
#include 
#include 
using namespace std;
int main(){
    char str[50];
    double num;
    strcpy(str, "9.15");
    sscanf(str, "%lf", &num);
    printf("num = %lf\n", num);
    return 0;
}

输出结果:

num = 9.150000

sprintf

sprintf函数可以把格式化后的内容赋值给一个指定的字符串,如果成功,则返回写入的字符总数,不包括字符串追加在字符串末尾的空字符。如果失败,则返回一个负数。函数接口如下:

int sprintf(char *str, const char *format, ...)

其中str是待写入的字符串,format是格式化字符串。

实例

#include 
#include 
#include 
using namespace std;
int main(){
    char str[50];
    double num = 9.1509123;
    sprintf(str, "The price of the shirt is %.2lf pounds.", num);
    printf("%s\n", str);
    return 0;
}

输出结果:

The price of the shirt is 9.15 pounds.

你可能感兴趣的:(sscanf与sprintf函数)