sscanf函数简介

#include <stdio.h>

//从标准输入端(终端)读取
int scanf(const char *restrict format, ...);

//从文件中读取
int fscanf(FILE *restrict stream, const char *restrict format, ...);

//从字符串中读取
int sscanf(const char *restrict s, const char *restrict format, ...);

 sscanf从字符串s中按照format格式读取内容。

1. 从字符串中读取字符串

sscanf("hello world", "%s", buf);  // buf = hello ,从第一个非中止字符(空格,tab, 换行符)开始,到中止字符结束的第一个字符串

2. 从字符串中读取特定字符串

sscanf("hello12345world", "%[a-z]", buf); // buf=hello,读取到字符不是a-z为止, 如果是%[0-9],buf内容不变,因为第一个字符'h'不是0-9

sscanf("hello12345world", "%[^0-9]", buf); // buf=hello, 读取到字符是0-9为止, 字符串中可以有空格/tab/换行符

3.从字符串中忽略特定字符串 (%*忽略...字符串)

sscanf("hello12345world", %*[a-z]%[^a-z], buf);  // buf = 12345, 先忽略a-z之间的所有字符,即"hello",再读取字符不为a-z的字符串

猜你喜欢

转载自www.cnblogs.com/blackandwhite/p/12690539.html