简体   繁体   中英

switch case, user input, determine what character it is

I have a bunch of if statements. But I want to have that bunch of if statements in a switch. I try it like this:

// project_stringManipulation.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <cctype>

using namespace std;

int main()
{

    char input;
    cin >> input;

    switch (input)
    {
    case isalpha(input) :       
        cout << "That's an alphabetic character.\n";
    default:
        break;
    }


    cout << "Enter any character: ";
    cin.get(input);
    cout << "The character you entered is: " << input << endl;
    cin.get();
    if (isalpha(input))
        cout << "That's an alphabetic character.\n";
    cin.get();
    if (isdigit(input))
        cout << "That's a numeric digit.\n";
    cin.get();
    if (islower(input))
        cout << "The letter you entered is lowercase.\n";
    cin.get();
    if (isupper(input))
        cout << "The letter you entered is uppercase.\n";
    cin.get();
    if (isspace(input))
        cout << "That's a whitespace character.\n";

    cin.get();

    return 0;
}

But then I will get on this line:

case isalpha(input) :

The following error:

Severity    Code    Description Project File    Line    Suppression State
Error (active)      expression must have a constant value   project_stringManipulation  d:\Mijn Documents\VisualStudio2015\C++_Programs\Program_Nice\project_stringManipulation\project_stringManipulation.cpp  19  

How to do it on the correct way?

Thank you

When you write:

switch (input) {
    case {something}:
    break;
    ...
}

Then something is evaluated against input as in: (input == something) . If input is indeed equal to something then the case expression is true and your code will execute.

The issue is that you are evaluating input to the result of isalpha() which is a boolean.

Say input = "a" . Then, isAlpha(input) will return true .

Now your case says execute if "a" == true which is false, so your code doesn't execute.

If you wanted to structure this as a switch you could write something like:

switch (true) {
    case isalpha(input):
    //Do stuff
    break;
    ...
}

Also,

As mentioned by Dark Falcon in the comments, case statements must be constant values in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM