#include <stdio.h>
#include <stdlib.h>
int main(int atgc, int *argv[])
{
int a;
char buf[100] = {0};
FILE *file = NULL;
printf("请输入一个数字:");
scanf("%d", &a);
printf("a = %d\n", a);
sscanf("123456", "%2d", &a);
sscanf("abcdef", "%4s", buf); // 取指定长度的字符串
printf("a = %d\nbuf:%s\n", a, buf);
//取到指定字符为止的字符串
sscanf("123456 abcdedf", "%[^ ]", buf); //取遇到空格为止字符串
printf("取到指定字符为止的字符串:%s\n", buf);
sscanf("123456abcdedfBCDEF", "%[^A-Z]", buf); //取遇到大写字母为止的字符串
printf("取到指定字符为止的字符串:%s\n", buf);
// 取仅包含指定字符集的字符串
sscanf("123456abcdedfBCDEF", "%[1-9a-z]", buf); //取仅包含1到9和小写字母的字符串
printf("取仅包含指定字符集的字符串:%s\n", buf);
//获取两个指定字符之间的字符串
sscanf("iios/12DDWDFF@122", "%*[^/]/%[^@]", buf);
printf("取两个指定字符之间的字符串:%s\n", buf);
//给定一个字符串"hello, world",仅保留"world"
sscanf("hello, world", "%*s%s", buf); // %*s表示第一个匹配到的%s被过滤掉
printf("%s\n", buf);
//从文件中读取
file = fopen("hello.txt", "r");
if(NULL!= file)
{
fscanf(file, "%s", buf);
printf("从文件中读取:%s\n", buf);
}
fclose(file);
return 0;
}
C/C++中scanf、sscanf、fscanf函数用法
最新推荐文章于 2025-04-06 14:30:04 发布