string in switch

Pages: 12
@chervil
I think converting string to int can't help me.bacause if user inputs"as13js"it dosn't work.(but I'm not sure)
Then you can make a search in an array of acceptable responses. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const std::string responses[] = { "1", "2", "3", "Quit", "Add" };

int value = std::distance( std::find( std::begin( responses ), std::end( responses ), num ), std::begin( responses ) );

switch ( value )
{
   case 0:
      std::cout << responses[0] << " was entered\n";
      break;

   case 1:
      std::cout << responses[1] << " was entered\n";
      break;

   case 2:
      std::cout << responses[2] << " was entered\n";
      break;
  
   case 3:
      std::cout << responses[3] << " was entered\n";
      break;

   case 4:
      std::cout << responses[4] << " was entered\n";
      break;

   default:
      std::cout << "Error. Invalid input.\n";
      break;
}
Last edited on
any suggestions?(everybody!!!)
int value = std::distance( std::find( std::begin( responses ), std::end( responses ), num ), std::begin( responses ) );


can you explain about this line ,please??
It is written incorrectly.:) Shall be



int value = std::distance( std::begin( responses ), std::find( std::begin( responses ), std::end( responses ), num ) );

The internal algorithm std::find searches the given string in the array of responses. It returns the pointer to the target array element. Function std::distance returns the index of the element (or the size of the arrray of such element was not found). This value can be used in the switch statement.
Last edited on
Who can helps me with another method?
I'm not sure what it is you are looking for. Do you just want any method which works, or must the input be a string (for other reasons, not clear to me)?
There is a menu.user shoud choose one of the options(He or she shoud input one number between1and 8)
but maybe user inputs for example:"jhgjfkhgj87685nf"!we should have an error for she or he.
did you get it?
Ok I see that. From my point of view, you could get the input as a char, int or string. Whichever one you choose, you have to handle erroneous input.

One thing I don't understand. Have all the previous suggestions failed to work for you, or is this simply a matter of finding as many different solutions as possible to this task?
Last edited on
I used char but it has a problem.
if user inputs "1hnkdhcn", in switch statement case 1 runs and then shows:wrong number.
I don't know what to do...
You need to ignore the rest of the buffer:
1
2
3
char ch;
cin >> ch;
cin.ignore(80, '\n');


You can also just use an int:
1
2
3
4
5
6
7
8
int i;
while (!(cin >> i)
{
  cin.clear();
  cin.ignore(80,'\n');
  cout << "Not a number, try again: ";
}
cin.ignore(80,'\n');
I used all of these methods.But all of them have one problem:
If we input for example:"1gfvgvg" case 1 runs and then show:"not a number...."
I uesd function and this function shoud return:"1gfvgvg" to main funtion to compare"1gfvgvg" with cases. but it just return"1".I have that problem in all of above methods.
to compare"1gfvgvg" with cases.
Note, it is not possible to directly compare the string using a switch/case, so I'm still not entirely clear on the requirements.

Just to clarify the question (sorry about this).

If the user inputs this "1gfvgvg", then it is not acceptable to issue an error message and ask the user to try again.

Instead, the requirement is that the switch/case should issue the error message.

If I understand correctly, the approach below is not satisfactory, (even though in other respects working properly), because the error message is issued at line 41 instead of from line 29.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>

    using namespace std;

int getchoice();

int main()
{

    // user may select an option from 1 to 8
    // Must also handle erroneous input by the user.

    int  choice = getchoice();

    switch (choice)
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
            cout << "choice is " << choice << endl;
            break;
        default:
            cout << "choice was invalid" << choice << endl;
    }

    return 0;
}

int getchoice()
{
    cout << "Please choose a number from 1 to 8: ";
    string s;
    while (cin>>s && (s.size()!=1 || s<"1" || s>"8"))
    {
        cout << "\nnot a valid choice, please try again" << endl;
        cin.sync();
    }
    int n = s[0] - '0';
    return n;
}


If that is the correct explanation of the requirements, then function getchoice() could be modified to take a string parameter passed by reference, thus making the actual input available to the calling program. Also, the logic would require a change in order to return -1 for an invalid input.
Last edited on
Thank you Chervil.
It was a very good method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool IsInteger( const std::string s )
{
    if ( s.size() == 0 )
        return false ;

    if ( !(std::isdigit(s[0]) || s[0] == '-' || s[0]=='+') )
        return false ;

    for ( unsigned i=1 ;  i<s.size();  ++i )
        if ( !std::isdigit(s[i]) )
            return false ;

    return true ;
}


Right now I saw this code in another topic.
can you explain for me why is it more complex?
(I mean that is there any diffrence between this code and your code?)
Last edited on
The major difference in the code above is the return type bool. The function IsInteger() checks whether the string s contains a valid representation of an integer, and returns a true/false result. It doesn't actually convert the string to an integer.

The code is also incorrect, as the strings "+" and "-" would each be considered a valid integer, but they are not.

Another difference is the type of input it could handle. Let's say you want an integer between 1 and 8.

My code will accept values like this: "1", "7", "3" etc.
On the other hand, what about these: "007", "+2" etc? Those are valid integers in the range 1 to 8, but my code would reject them.

What it comes down to is to first define the required behaviour, then write the code (or re-use existing code if appropriate) to implement that behaviour. That stage, fully defining the requirements is the key to achieving a satisfactory solution.
Last edited on
Thank you so much.
I understood many things.
Topic archived. No new replies allowed.
Pages: 12