sscanf与sprintf函数

sscanf

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

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

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

实例

#include <iostream>
#include <cstdio>
#include <string.h>
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 <iostream>
#include <cstdio>
#include <string.h>
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.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容