我该怎么做?我希望它检查数字
cout<<"Enter your first number: ";
std::cin >> dblNumOne;
int i=0;
char str[]=dblNumkOne;
while (str[i])
{
if (isalpha(str[i])) printf ("character %c is alphabetic\n",str[i]);
else printf ("character %c is not alphabetic\n",str[i]);
i++;
}
答案 0 :(得分:2)
简单,只需遍历std :: string:
std::string dblNumOne;
std::cin >> dblNumOne;
for(unsigned int i = 0; i < dblNumOne.length(); i++)
{
if (isalpha(dblNumOne[i]))
{
printf ("character %c is alphabetic\n", dblNumOne[i]);
}
else
{
printf ("character %c is not alphabetic\n", dblNumOne[i]);
}
}
答案 1 :(得分:0)
一种方法是使用字符串而不是char,因为字符串具有length
函数
所以这样:
std::string dblNumOne;
std::cout<<"Enter your first number: ";
std::cin >> dblNumOne;
std::cout << dblNumOne.length() << endl;
如果你必须使用char,那么你可以通过检查代表字符串结尾的'\0'
值来完成它。
我的方法是使用字符串并获取它的长度,然后使用c_str()
函数将其转换为char数组。
答案 2 :(得分:0)
1)将字符串转换为char数组:
strcpy(charArray,stringArray.c_str());
来源:http://v2.cplusplus.com/forum/windows/71633/
2)使用isdigit
打印出是否是数字:
while (charArray[i]) {
if (isdigit(charArray[i])){
printf ("character %c is a digit\n",str[i]);
} else {
printf ("character %c is not a digit\n",str[i]);
}
i++;
}
如果它回答了您的问题或者引导您回答,请记得点击我答案左侧的灰色复选标记(✓)!
答案 3 :(得分:0)
如果您想检查数字,可以试试这个:
std::string str = "";
std::cout<<"enter string>>";
std::cin>>str;
int is_number = 0;
char filter[] = "0123456789";
for(int n=0; n<str.size(); ++n){
for(int i=0; i<10; ++i){
if(str[n] == filter[i]){
++is_number;
break; // found match, filter next char in str
}else if(str[n] != filter[i] && i == 9){
std::cout<<"'"<<str[n]<<"' is not a digit!\n";
}
}
}
if(is_number == str.size()){
std::cout<<"You entered a number";
}else std::cout<<"You didn't enter a number!";
或识别十进制数,你可以试试这个:
int is_number = 0, is_decimal = 0;
char filter[] = ".0123456789";
for(int n=0; n<str.size(); ++n){
for(int i=0; i<11; ++i){
if(str[n] == filter[i]){
if(filter[i] == '.'){
++is_decimal;
}
++is_number;
break;
}
}
}// for decimal
if(is_number == str.size() && is_decimal <= 1){
std::cout<<"You entered a number";
}else std::cout<<"You didn't enter a number!";