-8

Im trying to write some code that will only let one of four letters be entered in the argv[1] parameter. if it is another character the letter q should come up.

so ive written

#include <iostream>
#include <cstdlib>

char D, A , R, B;

if(argv[1] != D||A||R||B)
{
  cout << "Q" << endl;
  return(0);
}

can anyone please help me

dorie
  • 1

3 Answers3

2

This if(argv[1] != D||A||R||B)

is not proper syntax

D,A,R, and B have not been initialized to anything! They are what you call variables.

nor do you have a main() function. You are missing a lot here, but I will answer how to check for the right char.

you will probably be better served by a switch statement:

switch (*argv[1])
{
    case 'D':
    case 'A':
    case 'R':
    case 'B':
       cout << "Not Q" << endl;
       break;
    case 'Q':
       cout << "We have a Q" << endl;
       break;
    default: 
       cout << "unknown char" << endl;
       break;
}

There are a lot of other things we could get into here, such as how to properly structure a program, or general C/C++ questions, but this should get you at least started.

  • @phresnel: sorry `*argv[1]`.. or even strcmp.. but this question has a lot left for it. –  Jul 25 '12 at 13:18
0

This is not possible in C++. You have to

if (argv[1] != D && argv[1] != A && ...)

and generally it is better to check how many parameters there actually are (though argv[0] and argv[1] are always present).

Also, you lack a main() function and therefore not even have char *argv[] defined:

int main (int argc, char *argv[]) {
 ...
}
Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
0

A third option would be in C++11:

#include <set>
#include <iostream>

int main(int argc, char** argv) {
  if (argc < 2)
    return 1;

  // here is the actual check:
  if (std::set<char>{'D','A','R','B'}.insert(argv[1][0]).second) {
    std::cout << "Q" << std::endl;
  } else {
    std::cout << "OK" << std::endl;
  }
  return 0;
}

This uses a temporary set that holds all values and an initialisation list to put the desired values in the set. Then it tries to insert the passed value (i.e. argv[1][0]) into the set and checks whether it was successful in inserting the element (accessing second), then it wasn't it and is therefore "wrong".

Note that we do not have to check for arvg[1][0] because every array has at least one element located at position 0.

bitmask
  • 32,434
  • 14
  • 99
  • 159