#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
int
main(void)
{
char *str = "2007-01-21 12:53:25";
char dates[50];
int hour;
int min;
int sec;
int result;
result = sscanf(str, "%s %d:%d:%d", dates, &hour, &min, &sec);
if (result != 4)
{
fprintf(stderr, "Failed to scanf: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("%d %s %d:%d:%d\n", result, dates, hour, min, sec);
return 0;
}
#include <string.h>
#include <errno.h>
#include <stdlib.h>
int
main(void)
{
char *str = "2007-01-21 12:53:25";
char dates[50];
int hour;
int min;
int sec;
int result;
result = sscanf(str, "%s %d:%d:%d", dates, &hour, &min, &sec);
if (result != 4)
{
fprintf(stderr, "Failed to scanf: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("%d %s %d:%d:%d\n", result, dates, hour, min, sec);
return 0;
}
이상하게 sscanf() 왠지 모르게 어렵게 느껴져서 잘 사용을 안했었다. 그러다가 이번에 문자열 파싱하기가 귀찮아서 한번 써봤는데, 내가 생각하던대로 착착 파싱이 되지는 않는것 같다.
우선 위 예제에서 "2007-01-21" 이 부분은 하나의 문자열로 파싱이 되는것 같다. 원래 내가 원했던 바는 아래와 같다.
char *str = "2007-01-21 12:53:25";
char year[5];
char month[3];
char day[3];
int hour;
int min;
int sec;
sscanf(str, "%s-%s-%s %d:%d:%d", year, month, day, hour, min, sec);
요렇게 하면 아래와 같이 파싱이 될 줄 알았는데..
year = "2007";
month = "01";
day = "21";
hour = 12;
min = 53;
sec = 25;
char year[5];
char month[3];
char day[3];
int hour;
int min;
int sec;
sscanf(str, "%s-%s-%s %d:%d:%d", year, month, day, hour, min, sec);
요렇게 하면 아래와 같이 파싱이 될 줄 알았는데..
year = "2007";
month = "01";
day = "21";
hour = 12;
min = 53;
sec = 25;
그런데 이렇게는 안되는것 같다. 정수형으로 빼낼 경우에는 내가 생각하는대로 되는것 같은데 문자열로 빼낼때는 공백을 구분자로 해야만 가능한건가? 아무튼 생각되로 안되는군. 역시 이상하게 sscanf()는 어렵게 느껴져..

comments
comments rss (+댓글 쓰러가기)sscanf(str, "%4[0-9]%*[ -]%2[0-9]%*[- ]%2[0-9] %d:%d:%d", year, month, day, &hour, &min, &sec);
와 같은 패턴매칭을 이용한 방법도 가능합니다.