2

I am trying to use a switch statement to start function calls. The value that needs to be passed into the switch statement in an argument that comes from the command line arguments, meaning that it is stored in argv[]. In my case, this argument is known to be stored in argv[5]. My problem is that I do not know how to properly convert or store the value found in argv[5] so that it can be read by the switch statement. I have tried using char*, char[], and string as the data type of my variable 'verbosity'

The error that I keep getting is this: statement requires expression of integer type ('char *' invalid) switch(verbosity) ^ ~~~~~~~~~

And my code is as follows:

char* verbosity = argv[5];
cout << endl << verbosity;

switch(verbosity)
{
case 'vlow':
{
   vlow();//calls vlow function
   break;
}
case 'vmed':
{
   vmed();//calls vmed function
   break;
}
case 'vhigh':
{
   vhigh();//calls vhigh function
   break;
}
default:
   break;
}

Is there a certain format that I should be using to pass a string from argv[] into my switch statement?

surelyq
  • 21
  • 1
  • 5
  • 1
    The error is telling you that you cannot use that data type with a `switch` statement. You must use an `int` – Ryan J Sep 02 '14 at 03:16
  • So even if argv[5] was converted to a string, a string data type would not be able to be passed into my switch statement? It only takes type int as a parameter? – surelyq Sep 02 '14 at 03:18
  • More precisely, you can only switch on integral or enumeration types (as well as class types that unambiguously convert to an integral or enumeration type). So `long` would work as well as `int`. – Luc Danton Sep 02 '14 at 03:24

1 Answers1

7

'vlow' is a a multicharacter literal, not a string literal.

To compare C-style strings, use std::strcmp like this:

if (std::strcmp(verbosity, "vlow") == 0)
{
   //process
}

Notice the use of "vlow" with double quotes.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294