-5

So I recently started with C++ and one challenge is to create a program that asks for two numbers and it has to say either if; one of the numbers is positive, both are positive or neither are positive. I tried to make a switch structure without if's but It does not seem to work out. Here's my code.

#include <iostream>
using namespace std;

int main()
{
    int number;
    int number2;

    cout <<"Introduce two numbers:" ;
    cin >> number, number2;
    switch(number)
    {
    case (number > 0) (number2 > 0): cout <<"Both numbers are positive.";
    break;
    case (number > 0) (number2 < 0): cout <<"One of the numbers is positive.";
    break;
    case (number < 0) (number2 > 0): cout <<"One of the numbers is positive.";
    break;
    case (number < 0) (number2 < 0): cout <<"None of the numbers are positive.";
    break;
    default: cout <<"It must be a number.";
}
    return 0;
}

The compilation errors I get are the following. In function 'int main()':

[Error] 'number' cannot appear in a constant-expression

[Error] 'number2' cannot appear in a constant-expression

[Error] a function call cannot appear in a constant-expression

[Error] 'number' cannot appear in a constant-expression

[Error] 'number2' cannot appear in a constant-expression

[Error] a function call cannot appear in a constant-expression

[Error] 'number' cannot appear in a constant-expression

[Error] 'number2' cannot appear in a constant-expression

[Error] a function call cannot appear in a constant-expression

[Error] 'number' cannot appear in a constant-expression

[Error] 'number2' cannot appear in a constant-expression

[Error] a function call cannot appear in a constant-expression

Alex
  • 1
  • You should start with a decent book on the language. You can't input 2 numbers like that, and `case` statements don't behave that way. – Phil M Feb 06 '19 at 01:02
  • There is no guessing at syntax. If you have even a shred of doubt about the proper syntax or language use -- look it up. It will save you untold amounts of time in the long run. Try something, compile, fail, try something else, compile, fail ... ends up going nowhere. – David C. Rankin Feb 06 '19 at 01:21
  • [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Stop guessing, start reading. – molbdnilo Feb 06 '19 at 03:28

1 Answers1

1

The issue that you are running into is that the cases in a switch statement can only take constants.

For example this is valid:

switch (number)
{
case 0:
    // Do something because number is 0
    break;
case 1:
    // Do something because number is 1
    break;
case -5:
    break;
//etc...
}

Basically you can't use variables after the case keyword. So you'll need to use ifs to do what you want, it isn't possible with a switch.

Some more reading on switch-statements: http://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm

Omada
  • 784
  • 4
  • 11