c++中检查字符串的长度和字母
Checking a string for its length and letters in C++
我需要写一个函数,将阻止用户输入任何字母,只有数字,它应该是7位,用户不能输入少于7或更多,用户也不能输入数字和字母(如12345ab)。我该怎么做呢?以下是我到目前为止想到的函数:
对于字符串的长度:
void sizeOfString(string name)
{
while (name.length() < 7 || name.length() > 7)
{
cout << "Invalid number of digitsn";
cin >> name;
}
}
对于字母:
bool containLetters(string test)
{
if (test.find_first_not_of("abcdefghijklmnopqrstuvwxyz") !=std::string::npos)
return true;
else
return false;
}
但它并没有真正起作用。你们有什么建议?
使用isalpha()
函数
bool isvalid(string string1){
bool isValid = true;
double len = string1.length();
for (int i=0;i<len;i++){
if(isalpha(string1[i])){
isValid = false;
}
}
if(len != 7){
isValid = false;
}
return isValid;
}
进行测试cout << isvalid("1234567"); //good
cout << isvalid("1s34567"); //bad
//etc
相关文章:
- 在编译时检查字符串文本的长度
- 检查字符串是否"null" C++
- 我应该如何解析和检查字符串?
- 检查字符串是否为整数
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 如何检查字符串中是否有重复的负号?例如 --1
- 如何检查字符串是否正确以将其转换为 int?
- 程序检查字符串是否只包含 1 和 0?
- 检查字符串是否是拉平德罗姆
- 检查字符串 c++ 的形式
- 如何检查字符串格式在读取C++文本文件时是否有效?
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- gtest:检查字符串是否等于两个字符串之一
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何检查字符串是否以C++中的"ed"结尾;
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 检查字符串是否仅包含字母
- 检查字符串中的小写字符或空格.布尔值不起作用
- 检查字符串是否有多个逗号相邻 c++