验证从std::cin中获取的字符*的长度
Validate the length of a char * taken from std::cin
我有一个名为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";
}
为用户输入使用更大的缓冲区,并检查缓冲区的最后一个元素。
相关文章:
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 从 std::vector<无符号字符>切片中提取 int?
- 字符转换功能 std::isupper() & std::islower() C++17
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 为什么 std::string_view 比常量字符*快?
- std::stringstream 返回字符 *
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- 在 std::vector<无符号字符中存储任意数据的方法>
- 为什么从 std::cin 读取输入后右括号字符的值有时不是")"?
- "std::string"是否将其字符作为签名字符在内部存储?
- std::stoi 只转换前几个字符
- std::可选实现为联合与字符[]/aligned_storage
- C++ 无法将 std::vector<BYTE> 转换为字符串或字符数组
- 如何使用 std::copy 当类有"无符号字符和运算符[]"时
- C++ 从 std::string 中删除所有非数字字符
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- C++ 如何查找下一个字符 std::cout 是否位于控制台行的开头