C++中sscanf和sprintf字符串的处理利器

一、理解与用法

scanf("%d", &n);
printf("%d", n);

scanf(screen, "%d", &n);
printf(screen, "%d", n);
就是可以理解为scanf输入其实是把screen的内容一%d格式传输到n中,而printf的输出则是把n以%d的格式传输到screen上。
  1. 接下来我们讲解sscanf和sprintf,均在头文件stdio.h中。
  2. sscanf和sprintf格式和上面一样,只不过把screen换成了字符数组(假设定义了一个char数组str[100]),如下:
sscanf(str, "%d", &n);
sprintf(str, "%d", n);

二、例子

#include<stdio.h>
int main(){
      int n;
      double db;
      char str[100] = "2048:3.14, hello", str2[100];
      sscanf(str, "%d:%lf,%s", &n, &db, str2);
      printf("n = %d, db = %.2f, str2 = %s\n", n, db, str2);
      return 0;
}

out:
n = 2048, db = 3.14, str2 = hello

#include<stdio.h>
int main(){
      int n = 12;
      double db = 3.1415;
      char str[100], str2[100] = "good";
      sprintf(str, "%d:%.2f,%s\n", n, db, str2);
      printf("str = %s\n", str);
      return 0;
}

out:
str = 12:3.14,good
posted @ 2020-05-21 21:24  睿晞  阅读(1303)  评论(0编辑  收藏  举报