简体   繁体   English

如何限制字符长度

[英]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.我知道人们会立即看到标题并说:“使用字符串”或“字符只能是 1 的长度”,但这些都有问题。

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.首先,由于稍后在代码中使用 switch 语句,我的变量必须保留为 char 以便它不会导致任何错误,对于测试期间的第二个答案,我发现即使我输入了多长度输入它只会将每个字符分别运行到我不希望发生的 switch 语句中。 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.请注意,我至少尝试过使用 strlen 和 size 函数,但无济于事。

Well, use string , because char can only be length of 1.好吧,使用string ,因为char只能是 1 的长度。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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