简体   繁体   中英

How to limit char length

I know people will immediately look at the title and just say: "Use String" or "Char can only be length of 1" but there are problems with those.

For the first, due to later on in the code using a switch statement my variable must stay as a char so that it does not cause any errors, and for the second answer during testing I found out that even if I entered a multi-length input it would just run each character into the switch statement separately which I do not want to happen. Any help is welcomed, oh and here's the code:

char input;
do {
    cout << "Please enter a number from 1 to 4.";
    cin >> input;
    if (sizeof(input)!=1) {
        cout << "Please just enter a number";
    }
    else {

        switch (input) {

        case '1': {
            cout << "One";
            break;
        }

        case '2': {
            cout << "Two";
            break;
        }

        case '3': {
            cout << "Three";
            break;
        }

        case '4': {
            cout << "Four";
            break;
        }

        default:

            cout << "Enter only a number from 1-4!";

        }

    }
    
} while ((input) != '4');

Note that I have at least attempted to use strlen and the size functions but to no avail.

Well, use string , because char can only be length of 1.

std::string input;
std::cin >> input;
if (input.size() != 1) {
  std::cout << "Wrong input";
} else {
  switch (input.front()) {
  case '1': 
  // ...
  }
}

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