算法学习之输入…sscanf()
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//sscanf()函数
//sscanf的作用:
//从一个字符串中读进于指定格式相符的数据。
//利用它可以从字符串中取出整数、浮点数和字符串。
//sscanf和scanf的区别:
//scanf是以键盘作为输入源,
//sscanf是以字符串作为输入源。
int main()
{
/*
int day,year;
char weekday[20],month[20],dtm[100];
strcpy(dtm,"Saturday March 25 1989");
sscanf(dtm,"%s %s %d %d",weekday,month,&day,&year);
printf("%s %d,%d=%s\n",month,day,year,weekday);
//cout << "Hello world!" << endl;
*/
//取指定长度的字符串
char str[100];
sscanf("12345","%4s",str);
printf("%s\n",str);
//格式化时间
int year,month,day,hour,minute,second;
sscanf("2013/02/13 14:55:34","%d/%d/%d %d:%d:%d",&year,&month,&day,&hour,&minute,&second);
printf("time=%d-%d-%d %d:%d:%d\n",year,month,day,hour,minute,second);
char str1[100];
//加上*表示跳过
sscanf("1234abcd","%*d%s",str1);
printf("%s\n",str1);
//取到指定字符为止的字符串
char str2[100];
sscanf("1234+abc","%[^+]",str2);
printf("%s\n",str2);
//取遇到小写字母为止的字符串
char str3[100];
sscanf(" 1234+ 1234abc 1234","%[^a-z]",str3);
printf("str3=%s\n",str3);
//取仅包含数字和小写字母的字符串
char str4[100];
sscanf("123456abcdefBFRGTY7890","%[1-9a-z]",str4);
printf("%s\n",str4);
return 0;
}
来源:CSDN
作者:Stone 不会喝水
链接:https://blog.csdn.net/qq_16497423/article/details/104157255