So basically, I'm creating a switch statement that if the user enters a p or if they enter a P it will still work, any ideas? Thank you

Dani AI

Generated

Quick summary building on the replies above: 's 'p' || 'P' idea doesn't do what was intended (it evaluates to a boolean). 's fall-through case labels are the simplest correct fix for a few letters, while and point toward normalizing case first. For maintainability and fewer duplicated labels, canonicalize the input to a single case and then switch on that.

A compact, safe pattern is to convert the character with the standard library before the switch. Note the cast to unsigned charstd::tolower expects values representable as unsigned char (or EOF), so skip the cast and you risk undefined behavior on negative char values:

#include <cctype>

char choice = /* input */;
unsigned char uc = static_cast<unsigned char>(choice);
char c = static_cast<char>(std::tolower(uc));  // canonical lower-case
switch (c) {
    case 'p': /* handle */ break;
    case 's': /* handle */ break;
}

Why the cast and why care about locales: the C++ std::tolower in <cctype> works for byte-by-byte case conversions and requires the unsigned-char cast to be portable; for language-specific rules or non-ASCII characters you need locale-aware facets or a Unicode-aware library. See the standard documentation for details on behavior and pitfalls: std::tolower (cppreference) and std::ctype facet (cppreference).

Troubleshooting tips: read input into a std::string and take the first non-whitespace character if users may type more than one char; always check for EOF; avoid ASCII bit hacks in portable code unless you're certain the input is plain ASCII and performance is critical.

Recommended Answers

All 4 Replies

switch (choice) 
{
 case 'p' || 'P': // do this
 break;
case 's' || 'S': // do that
}

won't work

Convert the string to evaluate to lower case, then use it.
I prefer if-else statments, of stings for input.

For ASCII
In a loop of string size:

if (is upper case(91< && 64>)) then
    swap_case()

Swap function:

function swap_case(&character)
    character XOR 32

Or for a more reliable solution (ei for more than just ASCII) you can use tolower() and toupper() functions found in the cctype header

Chris

switch (choice) 
{
 case 'p' || 'P': // do this
 break;
case 's' || 'S': // do that
}

won't work

Indeed. 'p' || 'P' would expand to a bool value of true, as will 's' || 'S'. Compilers will generally refuse to compile the above, as particular cases of a switch statement are not allowed to be duplicated.

Try this instead;

switch (choice) 
{
 case 'p':
 case 'P': // do this
 break;
case 's':
case 'S': // do that
  break;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.