我试过用,
if(isalpha(card[i].name))
...
但它说我不能用char类型这里是我的代码: 这是结构:
struct firm {
unsigned egn;
char name[80];
char lastname[80];
char department[80];
unsigned salary;
}card[100];
这是我想要检查的函数,如果只有字母继续:
void enter()
{
int i, n;
char temp[80];
do{
cout<<"Enter how many workers you want to add: ";cin>>n;
}while(!(n>0 && n<101));
for(i=top;i<n;i++)
{/*ЕГН + проверка*/
cout<<"Enter EGN: ";do{
cin>>temp;
if((strlen(temp)!=10))
cout<<"Enter EGN: ";
}while(strlen(temp)!=10);
card[i].egn = (unsigned) atoi (temp);
/*Име Фамилия*/
cout<<"Enter name(only letters): ";cin>>card[i].name;
cout<<"Enter lastname(only letters): ";cin>>card[i].lastname;
cout<<"Enter department: ";cin>>card[i].department;
cout<<"Enter salary: ";cin>>temp;
card[i].salary = (unsigned) atoi (temp);
}
}
当我尝试使用这种代码时:
cout<<"Enter name(only letters): ";do{
cin>>card[i].name;
if(isalpha(card[i].name))
.....;
它说我不能在int中使用char(isalpha使用int?)
答案 0 :(得分:2)
你需要在字符串的每个字符上循环,isalpha()
只测试一个字符。
答案 1 :(得分:1)
您不能在整个isalpha
数组上使用char
,只能在单个字符上使用char
。要检查std::all_of
数组中的每个字符是否按字母顺序排列,您可以使用auto name_begin = std::begin(card[i].name);
auto name_end = std::end(card[i].name);
bool name_alpha = std::all_of(name_begin, std::find(name_begin, name_end, '\0'), std::isalpha);
if (name_alpha) {
std::cout << "It's alphabetical!" << std::endl;
}
算法:
char* name_begin = card[i].name;
bool name_alpha = std::all_of(name_begin, name_begin+std::strlen(name_begin), std::isalpha);
if (name_alpha) {
std::cout << "It's alphabetical!" << std::endl;
}
如果您使用的编译器没有必要的C ++ 11支持,则可以执行以下操作:
bool name_alpha = true;
for (char* character = card[i].name; *character != '\0'; character++) {
if (!std::isalpha(*character)) {
name_alpha = false;
break;
}
}
if (name_alpha) {
std::cout << "It's alphabetical!" << std::endl;
}
然后是无聊的方式而不使用标准库算法:
{{1}}
答案 2 :(得分:0)
问题是name本身就是一个chars数组,所以你需要测试每个元素是这样的:
.....
cout<<"Enter name(only letters): ";do{
cin>>card[i].name;
bool bIsAlpha = true;
for (int j = 0; j < strlen(card[i].name); ++j)
{
if(!isalpha(card[i].name[j]))
{
bIsAlpha = false;
break;
}
}
if (bIsAlpha)
{
.....;
}