views:

1222

answers:

5

Hi,

I'm passing some numeric arguments while creating a process (in VC++)

I'm stuck at casting LPTSTR to int.

Thanks in advance,

+1  A: 

Try the atoi() function (or the appropriate version if you're using wide characters) to convert strings to integers.

Greg Hewgill
What if it's a wide char? Then you'd have to use wtoi().
Ates Goral
doesn't windows have this "_tcatoi" or whatever its called?
Johannes Schaub - litb
Yeah they're _ttoi and _tstoi.
Ates Goral
+9  A: 

A LPTSTR is just a Long Pointer to a char or wide-char string.

Use _ttoi or _tstoi for a character-width-agnostic way of doing the conversion.

Also see

Ates Goral
A: 

LPTSTR is a pointer to a string so you shouldn't cast it to an int if what you want is an int representing the value of string.

If you know that the string contains digits, e.g. "1234" you should be able to use the _wtoi function to convert it to an int

e.g.

int num = _wtoi(foo);

where foo is a LPTSTR.

edit: The above only works properly if the LPTSTR is a UNICODE string. i.e. _UNICODE is defined. If it isn't you should use atoi.

See http://msdn.microsoft.com/en-us/library/yd5xkb5c(VS.80).aspx

Glen
+1  A: 

My advice would be to use something like _tcstol rather than _ttoi, so you can handle error conditions such as non-digits in the string. For instance:

int result = atoi("0");
result = atoi("foo");

In both cases the result will be 0, but only in the second case there is an error in conversion.

Nemanja Trifunovic
+1  A: 

Gack! What exactly are you trying to do? Is your problem on the parent process side (which calls CreateProcess() ) or on the child process side?

There are several ways of communicating parameters from a parent process to a child process created by the CreateProcess() function. If you can encode those parameters as a reasonably-sized string, then passing them through command-line parameters (the lpCommandLine parameter of CreateProcess) is probably the most straightforward & portable, with environment variables 2nd.

If you have a data structure you can't encode in a reasonably-sized string (either because it's a large amount of memory, or it's not easily serialized), then you need to resort to some method of interprocess communication. A file or a block of shared memory are two ways of doing this. In either case you need to come up with an agreed-upon location for the child to find this (a filepath in the case of a file, or the name of the shared memory block), and then pass this string as a command-line parameter or environment variable.

If you're trying to parse the lpCommandLine parameter within the child process, then it's what other people have suggested.

Jason S