在这里编码很新。我们正在使用isalpha函数,但在将其与字符串配合使用时遇到麻烦。我的程序将提示用户输入单词,然后该功能将检查单词是否包含任何特殊字符。基本上,我的代码只会说所有字符都是特殊字符,如果只有一对,则不会。我假设这与我的for循环有关,但是我无法弄清楚如何使其工作。我搜索了很多内容,但在C ++中找不到太多帮助。
这是我的功能。任何帮助表示赞赏。
//*****IsAlphaStr*****
//This function returns true if the cString passed contains all alphabetic characters.
//If the parameter does not contain all alpha characters, a value of false is returned.
bool IsAlphaStr(char wordcheck[25], bool alphabetic)
{
int i = 0;
int n = 0;
for (int i = 0, n = strlen(wordcheck); i < n; i++)
{
if (isalpha(wordcheck[i]) == 0)
alphabetic = false;
else
alphabetic = true;
}
return alphabetic;
}
如前所述,IsAlphaStr
仅true
当所有给定字符均为字母时才返回。这可以通过在条件break
的false
分支中添加a来实现if
,这将停止for
循环的进一步执行。
if (isalpha(wordcheck[i]) == 0)
{
alphabetic = false;
break;
}
整个测试程序为:
#include <iostream>
//*****IsAlphaStr*****
//This function returns true if the cString passed contains all alphabetic characters.
//If the parameter does not contain all alpha characters, a value of false is returned.
bool IsAlphaStr(char wordcheck[25], bool alphabetic)
{
int i = 0;
int n = 0;
for (int i = 0, n = strlen(wordcheck); i < n; i++)
{
if (isalpha(wordcheck[i]) == 0)
{
alphabetic = false;
break;
}
else
alphabetic = true;
}
return alphabetic;
}
int main()
{
char test1[25] = "abcdefghijklmnopqrstuvwx";
char test2[25] = "0123456789ABCDEFGHIJKLMN";
char test3[25] = "abcdefghijklmnopqres++-A";
char test4[25] = "abcdefABCDEF";
bool alphabetic = false;
alphabetic = IsAlphaStr(test1, alphabetic);
std::cout << "test1 = " << alphabetic << std::endl;
alphabetic = IsAlphaStr(test2, alphabetic);
std::cout << "test2 = " << alphabetic << std::endl;
alphabetic = IsAlphaStr(test3, alphabetic);
std::cout << "test3 = " << alphabetic << std::endl;
alphabetic = IsAlphaStr(test4, alphabetic);
std::cout << "test4 = " << alphabetic << std::endl;
return 0;
}
输出为:
test1 = 1
test2 = 0
test3 = 0
test4 = 1
希望能帮助到你?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句