Scanning & extracting from CString
-
Anybody can show me an easy way to extract words from a string. Say I have the CString "03 March 2005" and I want an integer with the day, a string with month and an integer with year. Thanks.
-
Anybody can show me an easy way to extract words from a string. Say I have the CString "03 March 2005" and I want an integer with the day, a string with month and an integer with year. Thanks.
Several ways:
CString str = "03 March 2005";
int nDay = atoi(str); // stops at the first non-numeric character
int nYear = atoi(str.Right(4));
or
int nYear;
char szMonth[6];
sscanf(str, "%d %s %d", &nDay, szMonth, &nYear);
or
CString strMonth = str.Mid(3, 5);
or
int nSpace1 = str.Find(' ');
int nSpace2 = str.ReverseFind(' ');
strMonth = str.Mid(nSpace1 + 1, nSpace2 - nSpace1 - 1);There are probably more, but I think you get the idea.
"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
-
Several ways:
CString str = "03 March 2005";
int nDay = atoi(str); // stops at the first non-numeric character
int nYear = atoi(str.Right(4));
or
int nYear;
char szMonth[6];
sscanf(str, "%d %s %d", &nDay, szMonth, &nYear);
or
CString strMonth = str.Mid(3, 5);
or
int nSpace1 = str.Find(' ');
int nSpace2 = str.ReverseFind(' ');
strMonth = str.Mid(nSpace1 + 1, nSpace2 - nSpace1 - 1);There are probably more, but I think you get the idea.
"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
sscanf is evil! I like to use it for buffer overruns myself :mad:
-
Several ways:
CString str = "03 March 2005";
int nDay = atoi(str); // stops at the first non-numeric character
int nYear = atoi(str.Right(4));
or
int nYear;
char szMonth[6];
sscanf(str, "%d %s %d", &nDay, szMonth, &nYear);
or
CString strMonth = str.Mid(3, 5);
or
int nSpace1 = str.Find(' ');
int nSpace2 = str.ReverseFind(' ');
strMonth = str.Mid(nSpace1 + 1, nSpace2 - nSpace1 - 1);There are probably more, but I think you get the idea.
"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
Thank you!