YumYumYum YumYumYum - 4 years ago 89
C++ Question

C++ impossible to type cast?

How to get command line argument 'up' or 'down' or values between 0 till 0.50, 1? (where i must have to use _TCHAR* argv[])? it is impossible to make it working, is there any genius.

int _tmain(int argc, _TCHAR* argv[]) {
double SDK;

// command line input:
// user.exe up
// user.exe down
// user.exe 0.50
if (argv[1] == 'up') {

SDK= _tstof(0.85); // FAIL _T or (TCHAR*) or ...
}
else if(argv[1]== 'down') {
SDK= _tstof(0.50); // FAIL _T or (TCHAR*) or ...
}
else {
SDK= _tstof(argv[1]); // This works
}

//
// 3rd party SDK needs _TCHAR* argv[]
//

}

Answer Source

Your code has multiple problems:

if (argv[1] == 'up')

This will not work. In C/C++ you have to use " for string literals. Also, you are comparing the pointers, instead of the strings.

if(strcmp(argv[1], "up") == 0)

Another issue is the usage of _tstof which converts a string to a float while you are using a float as if it were a pointer to a string to convert it to a float which it already is.

The last line:

SDK= _tstof(argv[1]);

also may not work unless your argument is a string representation of a number. So you might check if the string is really a number and not something else.

#include <Windows.h>
#include <WinNT.h>
int _tmain(int argc, TCHAR* argv[]) {
  double SDK;

  // command line input: 
  // user.exe up
  // user.exe down
  // user.exe 0.50
  if (strcmp(argv[1], "up") == 0)
    SDK= 0.85;
  else if(strcmp(argv[1], "down") == 0)
    SDK= 0.50;
  else
    SDK = atof(argv[1]);

  //
  // 3rd party SDK needs _TCHAR* argv[]
  //
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download