Skip to main content
gamedev.net
🔒 Locked

swscanf

Started by Glyph 1 reply 500+ views
Original Post
Glyph
Glyph
Hello, I am having a problem using swscanf under VC++ 6.0. My program crashes with an Access Violation during the swscanf call. What am I doing wrong?
  
#include <wchar.h>

int main ()
{
	const wchar_t* versionString = L"2.1.3.2070";
	int major = 0;
	int minor = 0;
	int revision = 0;
	int build = 0;

	swscanf (versionString,
		 L"%d.%d.%d.%d",
		 &major,
		 &minor,
		 &revision,
		 &build);

	wprintf (L"Major    = %4d\n"
		 L"Minor    = %4d\n"
		 L"Revision = %4d\n"
		 L"Build    = %4d\n",
		 major,
		 minor,
		 revision,
		 build);

	return 0;
}
   
I'd also be interested in the 'proper C++ way' to take a string in the form "2.1.3.2070" and extract the values 2, 1, 3, and 2070 into four integers. Thanks in advance! -Glyph [edited by - Glyph on May 15, 2003 4:10:52 PM]
Glyph
Glyph
So I''ve tinkered a bit, and come up with the following workaround (read: hack)


  
#include <malloc.h>
#include <wchar.h>

int main ()
{
const wchar_t* versionString = L"2.1.3.2070";
int major = 0;
int minor = 0;
int revision = 0;
int build = 0;

wchar_t* myVersionString = wcsdup (versionString);

wchar_t* thisPortion = myVersionString;
wchar_t* nextPortion = wcschr (thisPortion, L''.'');
nextPortion [0] = L''\0'';
major = _wtoi (thisPortion);

thisPortion = nextPortion + 1;
nextPortion = wcschr (thisPortion, L''.'');
nextPortion [0] = L''\0'';
minor = _wtoi (thisPortion);

thisPortion = nextPortion + 1;
nextPortion = wcschr (thisPortion, L''.'');
nextPortion [0] = L''\0'';
revision = _wtoi (thisPortion);

thisPortion = nextPortion + 1;
build = _wtoi (thisPortion);

thisPortion = NULL;
nextPortion = NULL;
free (myVersionString);
myVersionString = NULL;

wprintf (L"Major = %4d\n"
L"Minor = %4d\n"
L"Revision = %4d\n"
L"Build = %4d\n",
major,
minor,
revision,
build);

return 0;
}

Seems kinda kludgey. Does anyone have a better way to do this? By the way... the original (with the swscanf) appears to work correctly under VC++ 7.0. Unfortunately, our project hasn''t gotten the green light to migrate to VC++ 7.0 yet, so for the moment I have to make due with 6.0. Any suggestions greatly appreciated!

-Glyph
Glyph
Glyph
Yet another hack. If I change the format string of the swscanf function to look like this:

L"%1d.%1d.%1d.%4d",

it works fine. Obviously assuming the number of digits in a version will never change is undesirable. There must be a better way...

-Glyph

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.