里面的函数问题
题目:创建一个程序,输出由8个随机大小写字母或数字组成的密码。允许输入重复的字符。必须用循环来做。
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <limits>
#include <ctime>
using namespace std;
int main() {
const int chars_in_password= 8;
char ch = 0;
srand(static_cast<unsigned int>(time(0)));
cout << "Your password is: ";
// We have to read at least one character - even if it's '#' - so do-while is best
for (int i = 0 ; i< chars_in_password ; i++)
while(true) {
// Character code is a random value between the minimum and maximum for type char
ch = numeric_limits<char>::min()+(((numeric_limits<char>::max()-numeric_limits<char>::min())*rand())/RAND_MAX);
if(!isalnum(ch))
continue;
else{
cout<<ch;
break;
}
}
cout << endl;
return 0;
}
关键问题是,标记红色的那一块,总是输出奇奇怪怪的字符,我试了一下即便把ch强制转换成char或者int型,让其只输出字母,或者只输出数字,也还是会有那些奇怪的字符,总之,只要用了cctype里的isdigit()或者isalpha()就出问题,输出很奇怪,最后无奈改成:
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <limits>
#include <ctime>
using namespace std;
int main() {
const int chars_in_password= 8;
char ch = 0;
srand(static_cast<unsigned int>(time(0)));
cout << "Your password is: ";
// We have to read at least one character - even if it's '#' - so do-while is best
for (int i = 0 ; i< chars_in_password ; i++)
while(true) {
// Character code is a random value between the minimum and maximum for type char
ch = numeric_limits<char>::min()+(((numeric_limits<char>::max()-numeric_limits<char>::min())*rand())/RAND_MAX);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){
cout<< ch;
break;
}
else if(ch>=0&&ch<=9){
cout<<static_cast<int>(ch);
break;
}
else
continue;
}
cout << endl;
return 0;
}
红色标记的是改了之后的,就可以出现想要的结果了,我不明白,为什么调用cctype里的函数会出现这种问题呢?即便强制转换也不行!