Picking from a list

Is there a better way to choose a number from a list other than a bunch of if statements. Essentially what i need is the user to input a number then using the number they entered the constants in the math are different.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

// this isnt my actual code just a quick example of what im talking about

cout << " please enter number" << endl;
float ans;
cin >> ans; 

if ( ans == 1 ) 
( do math with these constants) 

if (ans ==2) 
 ( do math with these constants) 

if ( ans == 3) 

ect.....


Last edited on
If the value is a float like in your example, then one can only use a bunch of if and else if statements.

Be careful with using the equality operator on FP numbers - they are not exact. There have been lots of topics about that on this forum.

Use a switch statement as long as the value of the variable in question is constant integral type. Make sure to have a default clause to catch bad input, I like to have a quit case as well. Put the whole thing in a bool controlled while loop:

http://www.cplusplus.com/forum/beginner/99203/#msg534078




HTH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

void do_math( const int (&a)[3] )
{
    std::cout << "do_math -" ;
    for( int v : a ) std::cout << ' ' << v ;
    std::cout << '\n' ;
}

int main()
{
    constexpr int constants[][3] = { {}, {0,1,2}, {4,5,6}, {7,8,9}, {10,11,12} } ;
    constexpr std::size_t n = sizeof(constants) / sizeof(*constants) ;

    std::size_t ans ; std::cout << "please enter number: " && std::cin >> ans ;
    if( ans>0 && ans<n ) do_math( constants[ans] ) ;
}

http://ideone.com/gprQ8H
Topic archived. No new replies allowed.