验证从std::cin中获取的字符*的长度

Validate the length of a char * taken from std::cin

本文关键字:字符 std cin 验证 获取      更新时间:2023-10-16

我有一个名为char * panimal_name的指针。该指针只能包含20个字符,如果用户输入更多字符,则必须要求用户重新输入。

我已经尝试过计算流中的字符数,也尝试过使用strlen(),但是我仍然有问题。

cout << "Enter Animal Name: ";
cin.ignore();
cin.getline(panimal_name, 20);

如有任何帮助,我们将不胜感激。

编辑:好吧,我只希望它最多能占用用户的20个字符。如果超过20,则应要求用户重新输入有效输入。然而,在这个设置中,它现在扰乱了我下一次输入的流。我之所以使用这个,而不是std::string,是因为我现在正在学习指针。

附言:我知道在这种情况下,为了方便使用,字符串可能会更好。

根据MSDN:

如果函数不提取任何元素或_Count-1元素,则调用设置状态(故障位)。。。

你可以检查故障位,看看用户输入的数据是否超过了缓冲区允许的数量?

您可以使用c++方法。。

std::string somestring;
std::cout << "Enter Animal Name: ";
std::cin >> somestring;
printf("someString = %s, and its length is %lu", somestring.c_str(), strlen(somestring.c_str()));

你也可以使用更多的c++方法

std::string somestring;
std::cout << "Enter Animal Name: ";
std::cin >> somestring;
std::cout << "animal is: "<< somestring << "and is of length: " << somestring.length();

我想你可以用cin对字符串做点什么来绕过cin肠道的工作方式。

考虑以下程序:

#include <iostream>
#include <string>
#include <limits>
// The easy way
std::string f1() {
  std::string result;
  do {
    std::cout << "Enter Animal Name: ";
    std::getline(std::cin, result);
  } while(result.size() == 0 || result.size() > 20);
  return result;
}
// The hard way
void f2(char *panimal_name) {
  while(1) {
    std::cout << "Enter Animal Name: ";
    std::cin.getline(panimal_name, 20);
    // getline can fail it is reaches EOF. Not much to do now but give up
    if(std::cin.eof())
      return;
    // If getline succeeds, then we can return
    if(std::cin)
      return;
    // Otherwise, getline found too many chars before 'n'. Try again,
    // but we have to clear the errors first.
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n' );
  }
}
int main () {
  std::cout << "The easy wayn";
  std::cout << f1() << "nn";
  std::cout << "The hard wayn";
  char animal_name[20];
  f2(animal_name);
  std::cout << animal_name << "n";
}

为用户输入使用更大的缓冲区,并检查缓冲区的最后一个元素。