【问题标题】:How to test a char array for letters only (including whitespaces)?如何仅测试字符数组(包括空格)?
【发布时间】:2015-06-27 03:49:09
【问题描述】:

我正在做一个基本信息输入的功能。此函数稍后将用于获取信息并存储在磁盘上。 我做了两次检查。 is_alpha 和 is_digit。 is_alpha 的问题是,如果它检测到空白(这不是我想要的),它会返回“0”。我正在输入“名称”,显然它可以包含空格! 你能告诉我如何制作一个方法来检查我的 char 数组是否是一个名字? (字母和空格)

class Bankaccount
{
protected:
int id;
char name[50];
char address[100];
char phone_no[50];
static int count;

public:
Bankaccount()
{

    count++;
    id = count;
}



bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
bool is_alpha(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
{cin.ignore(); return !s.empty() && it == s.end();}
}

void basics ()
    {system("cls");
    cout << "Enter Name (Letters only): " << endl;
    cin.ignore();
    cin.getline(name,50);


    {cout << "Enter Address: " << endl;
            cin.ignore();
cin.getline(address,100);
    cout << "Enter Phone Number (Digits only): " << endl;
    cin.ignore();
    cin.getline(phone_no,50);
    //CHECK FOR DIGITS ONLY
    bool temp=0;
    temp=is_number(phone_no);
    {while(temp!=1)
        {cout << "ReEnter Phone Number: " << endl;
        cin.ignore();
        cin.getline(phone_no,50);
        temp=is_number(phone_no);
        }
    }//while ends

    }



    {cout << "ReEnter Name: " << endl;
    cin.ignore();
    cin.getline(phone_no,50);

    cout << "Enter Address: " << endl;
            cin.ignore();
cin.getline(address,100);
    cout << "Enter Phone Number (Digits only): " << endl;
    cin.ignore();
    cin.getline(phone_no,50);
    //CHECK FOR DIGITS ONLY
    bool temp;
    temp=is_number(phone_no);
    if (temp==1)
    {}
    else {cout << "ReEnter Phone Number: " << endl;
    cin.ignore();
    cin.getline(phone_no,50);
    }
}

}

【问题讨论】:

  • 您可以使用 std::isspace 或 std::isblank 以及 std::isalpha。有什么问题?
  • 如何同时使用 isspace 和 isalpha?我是初学者。请帮忙!
  • 名称还可以包含连字符和撇号。最好做一个 is_validnamecharacter() 函数。
  • @Qurat_D 例如 if ( std::isalpha( c ) || std::isblank( c ) ) std::cout
  • 'isblank' 接受 int :/ 我的输入是 char 数组

标签: c++ string


【解决方案1】:

相信你知道c++内置了isalpha(char)的STL函数。

所以您要做的就是检查空格或字母(对于名称)。

让我帮你,请参考下面的代码:

bool isValidName(string word) {
    for(int i=0;i<(int)word.length();i++) {
        if ((word[i] != ' ') && (!isalpha(word[i])) {
            return false;
        }
    }
    return true;
}

请注意,我假设您在标题中声明以下内容:

using namespace std;

如果不是,那么你必须在任何与 std 相关的东西前面写 std:: 。例如std::string.

只需将名称传递给上述函数的参数即可。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 2011-01-03
    • 2015-01-13
    相关资源
    最近更新 更多