sprintf和sscanf

sprintf:把变量打印到字符串中,从而获得数字的字符形式(可以实现将整形转换成字符型)

sscanf: 从一个字符串中读进与指定格式相符的数据. 格式可以是整型数据等。

sprintf应用举例:

view plaincopy to clipboardprint?#include <stdio.h> 
int main ()
{
    char c[100];
    int k=255;
    sprintf(c,"%d",k);
    printf("%c",c[1]);
    return 0;
}
#include <stdio.h>
int main ()
{
char c[100];
int k=255;
sprintf(c,"%d",k);
printf("%c",c[1]);
return 0;
}

ssanf应用举例:

view plaincopy to clipboardprint?/* sscanf example */
#include <stdio.h> 
int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str[20], str1[20];
  int i;
  sscanf (sentence,"%s %*s%d %s",str,&i,str1);  //%*s 跳过此数据不读入 
  printf ("%s -> %d/n",str,i);
  printf("%s",str1);
  return 0;
}

转自:http://blog.csdn.net/wo175eufgnrfg/article/details/6415262
 
sscanf可以支持格式字符%[ ] 这为分析字符串提供了很大方便(其实scanf也支持%[ ]),先看一下%[ ] 格式:
(1)-: 表示范围,如:%[1-9]表示只读取1-9这几个数字 %[a-z]表示只读取a-z小写字母,类似地 %[A-Z]只读取大写字母
(2)^: 表示不取,如:%[^1]表示读取除'1'以外的所有字符 %[^/]表示除/以外的所有字符
(3),: 范围可以用","相连接 如%[1-9,a-z]表示同时取1-9数字和a-z小写字母
(4)原则:从第一个在指定范围内的数字开始读取,到第一个不在范围内的数字结束 %s可以看成%[ ] 的一个特例 %[^ ](注意^后面有一个空格!)

这样使用sscanf+%[ ]可以轻松的分析字符串,很多字符串问题便迎刃而解了

(1)常见用法。
char str[512] ={0};
sscanf("123456 ", "%s", str);
printf("str=%s\n", str);
操作后:str中为"123456"

(2)取指定长度的字符串。如在下例中,取最大长度为4字节的字符串。
sscanf("123456 ", "%4s", str);
printf("str=%s\n", str);
操作后:str中为"1234"

(3)取到指定字符为止的字符串。如在下例中,取遇到空格为止字符串。
sscanf("123456 abcdedf", "%[^ ]s", str);
printf("str=%s\n", str);
操作后:str中为"123456"

(4)取仅包含指定字符集的字符串。如在下例中,取仅包含1到9和小写字母的字符串。
sscanf("123456abcdedfBCDEF", "%[1-9,a-z]s", str);
printf("str=%s\n", str);
操作后:str中为"123456abcdef"

(5)取到指定字符集为止的字符串。如在下例中,取遇到大写字母为止的字符串。
sscanf("123456abcdedfBCDEF", "%[^A-Z]s", str);
printf("str=%s\n", str);
操作后:str中为"123456abcdef"

你可能感兴趣的:(printf)